Artem Senichev | e8837d5 | 2020-06-07 11:59:04 +0300 | [diff] [blame] | 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (C) 2020 YADRO |
| 3 | |
| 4 | #include "zlib_file.hpp" |
| 5 | |
| 6 | #include "zlib_exception.hpp" |
| 7 | |
| 8 | ZlibFile::ZlibFile(const std::string& fileName) |
| 9 | { |
| 10 | fd = gzopen(fileName.c_str(), "w"); |
| 11 | if (fd == Z_NULL) |
| 12 | { |
| 13 | throw ZlibException(ZlibException::create, Z_ERRNO, fd, fileName); |
| 14 | } |
| 15 | this->fileName = fileName; |
| 16 | } |
| 17 | |
| 18 | ZlibFile::~ZlibFile() |
| 19 | { |
| 20 | if (fd != Z_NULL) |
| 21 | { |
| 22 | gzclose_w(fd); |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | void ZlibFile::close() |
| 27 | { |
| 28 | if (fd != Z_NULL) |
| 29 | { |
| 30 | const int rc = gzclose_w(fd); |
| 31 | if (rc != Z_OK) |
| 32 | { |
| 33 | throw ZlibException(ZlibException::close, rc, fd, fileName); |
| 34 | } |
| 35 | fd = Z_NULL; |
| 36 | fileName.clear(); |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | void ZlibFile::write(const tm& timeStamp, const std::string& message) const |
| 41 | { |
| 42 | int rc; |
| 43 | |
SpencerKu | e9af83c | 2020-10-16 10:55:42 +0800 | [diff] [blame] | 44 | // Write time stamp. |
| 45 | // "tm_gmtoff" is the number of seconds east of UTC, so we need to calculate |
| 46 | // timezone offset. For example, for U.S. Eastern Standard Time, the value |
| 47 | // is -18000 = -5*60*60." |
| 48 | |
| 49 | rc = gzprintf(fd, "[ %i-%02i-%02iT%02i:%02i:%02i%+03ld:%02ld ] ", |
| 50 | timeStamp.tm_year + 1900, timeStamp.tm_mon + 1, |
| 51 | timeStamp.tm_mday, timeStamp.tm_hour, timeStamp.tm_min, |
| 52 | timeStamp.tm_sec, timeStamp.tm_gmtoff / (60 * 60), |
| 53 | abs(timeStamp.tm_gmtoff % (60 * 60)) / 60); |
| 54 | |
Artem Senichev | e8837d5 | 2020-06-07 11:59:04 +0300 | [diff] [blame] | 55 | if (rc <= 0) |
| 56 | { |
| 57 | throw ZlibException(ZlibException::write, rc, fd, fileName); |
| 58 | } |
| 59 | |
| 60 | // Write message |
| 61 | const size_t len = message.length(); |
| 62 | if (len) |
| 63 | { |
| 64 | rc = gzwrite(fd, message.data(), static_cast<unsigned int>(len)); |
| 65 | if (rc <= 0) |
| 66 | { |
| 67 | throw ZlibException(ZlibException::write, rc, fd, fileName); |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | // Write EOL |
| 72 | rc = gzputc(fd, '\n'); |
| 73 | if (rc <= 0) |
| 74 | { |
| 75 | throw ZlibException(ZlibException::write, rc, fd, fileName); |
| 76 | } |
| 77 | } |