| 1 | // |
|---|
| 2 | // Copyright(c) 2015-2018 Gabi Melman. |
|---|
| 3 | // Distributed under the MIT License (http://opensource.org/licenses/MIT) |
|---|
| 4 | // |
|---|
| 5 | |
|---|
| 6 | #pragma once |
|---|
| 7 | |
|---|
| 8 | #ifndef SPDLOG_H |
|---|
| 9 | #include "spdlog/spdlog.h" |
|---|
| 10 | #endif |
|---|
| 11 | |
|---|
| 12 | #include "spdlog/details/file_helper.h" |
|---|
| 13 | #include "spdlog/details/null_mutex.h" |
|---|
| 14 | #include "spdlog/sinks/base_sink.h" |
|---|
| 15 | |
|---|
| 16 | #include <mutex> |
|---|
| 17 | #include <string> |
|---|
| 18 | |
|---|
| 19 | namespace spdlog { |
|---|
| 20 | namespace sinks { |
|---|
| 21 | /* |
|---|
| 22 | * Trivial file sink with single file as target |
|---|
| 23 | */ |
|---|
| 24 | template<typename Mutex> |
|---|
| 25 | class basic_file_sink final : public base_sink<Mutex> |
|---|
| 26 | { |
|---|
| 27 | public: |
|---|
| 28 | explicit basic_file_sink(const filename_t &filename, bool truncate = false) |
|---|
| 29 | { |
|---|
| 30 | file_helper_.open(filename, truncate); |
|---|
| 31 | } |
|---|
| 32 | |
|---|
| 33 | protected: |
|---|
| 34 | void sink_it_(const details::log_msg &msg) override |
|---|
| 35 | { |
|---|
| 36 | fmt::memory_buffer formatted; |
|---|
| 37 | sink::formatter_->format(msg, formatted); |
|---|
| 38 | file_helper_.write(formatted); |
|---|
| 39 | } |
|---|
| 40 | |
|---|
| 41 | void flush_() override |
|---|
| 42 | { |
|---|
| 43 | file_helper_.flush(); |
|---|
| 44 | } |
|---|
| 45 | |
|---|
| 46 | private: |
|---|
| 47 | details::file_helper file_helper_; |
|---|
| 48 | }; |
|---|
| 49 | |
|---|
| 50 | using basic_file_sink_mt = basic_file_sink<std::mutex>; |
|---|
| 51 | using basic_file_sink_st = basic_file_sink<details::null_mutex>; |
|---|
| 52 | |
|---|
| 53 | } // namespace sinks |
|---|
| 54 | |
|---|
| 55 | // |
|---|
| 56 | // factory functions |
|---|
| 57 | // |
|---|
| 58 | template<typename Factory = default_factory> |
|---|
| 59 | inline std::shared_ptr<logger> basic_logger_mt(const std::string &logger_name, const filename_t &filename, bool truncate = false) |
|---|
| 60 | { |
|---|
| 61 | return Factory::template create<sinks::basic_file_sink_mt>(logger_name, filename, truncate); |
|---|
| 62 | } |
|---|
| 63 | |
|---|
| 64 | template<typename Factory = default_factory> |
|---|
| 65 | inline std::shared_ptr<logger> basic_logger_st(const std::string &logger_name, const filename_t &filename, bool truncate = false) |
|---|
| 66 | { |
|---|
| 67 | return Factory::template create<sinks::basic_file_sink_st>(logger_name, filename, truncate); |
|---|
| 68 | } |
|---|
| 69 | |
|---|
| 70 | } // namespace spdlog |
|---|