Artem Senichev | afc7373 | 2020-05-09 19:04:51 +0300 | [diff] [blame] | 1 | /** |
| 2 | * @brief Log file. |
| 3 | * |
| 4 | * This file is part of HostLogger project. |
| 5 | * |
| 6 | * Copyright (c) 2020 YADRO |
| 7 | * |
| 8 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 9 | * you may not use this file except in compliance with the License. |
| 10 | * You may obtain a copy of the License at |
| 11 | * |
| 12 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 13 | * |
| 14 | * Unless required by applicable law or agreed to in writing, software |
| 15 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 17 | * See the License for the specific language governing permissions and |
| 18 | * limitations under the License. |
| 19 | */ |
| 20 | |
| 21 | #include "log_file.hpp" |
| 22 | |
| 23 | #include "zlib_exception.hpp" |
| 24 | |
| 25 | LogFile::LogFile(const char* fileName) |
| 26 | { |
| 27 | fd_ = gzopen(fileName, "w"); |
| 28 | if (fd_ == Z_NULL) |
| 29 | throw ZlibException(ZlibException::Create, Z_ERRNO, fd_, fileName); |
| 30 | fileName_ = fileName; |
| 31 | } |
| 32 | |
| 33 | LogFile::~LogFile() |
| 34 | { |
| 35 | if (fd_ != Z_NULL) |
| 36 | gzclose_w(fd_); |
| 37 | } |
| 38 | |
| 39 | void LogFile::close() |
| 40 | { |
| 41 | if (fd_ != Z_NULL) |
| 42 | { |
| 43 | const int rc = gzclose_w(fd_); |
| 44 | if (rc != Z_OK) |
| 45 | throw ZlibException(ZlibException::Close, rc, fd_, fileName_); |
| 46 | fd_ = Z_NULL; |
| 47 | fileName_.clear(); |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | void LogFile::write(time_t timeStamp, const std::string& message) const |
| 52 | { |
| 53 | int rc; |
| 54 | |
| 55 | // Convert time stamp and write it |
| 56 | tm tmLocal; |
| 57 | localtime_r(&timeStamp, &tmLocal); |
| 58 | rc = gzprintf(fd_, "[ %02i:%02i:%02i ]: ", tmLocal.tm_hour, tmLocal.tm_min, |
| 59 | tmLocal.tm_sec); |
| 60 | if (rc <= 0) |
| 61 | throw ZlibException(ZlibException::Write, rc, fd_, fileName_); |
| 62 | |
| 63 | // Write message |
| 64 | const size_t len = message.length(); |
| 65 | if (len) |
| 66 | { |
| 67 | rc = gzwrite(fd_, message.data(), static_cast<unsigned int>(len)); |
| 68 | if (rc <= 0) |
| 69 | throw ZlibException(ZlibException::Write, rc, fd_, fileName_); |
| 70 | } |
| 71 | |
| 72 | // Write EOL |
| 73 | rc = gzputc(fd_, '\n'); |
| 74 | if (rc <= 0) |
| 75 | throw ZlibException(ZlibException::Write, rc, fd_, fileName_); |
| 76 | } |