epubgrep/src/log.cpp

96 lines
3.4 KiB
C++

/* This file is part of epubgrep.
* Copyright © 2021 tastytea <tastytea@tastytea.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "log.hpp"
#include "fs-compat.hpp"
#include "helpers.hpp"
#include <boost/locale/message.hpp>
#include <boost/log/core.hpp>
#include <boost/log/sources/logger.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <iostream>
namespace epubgrep::log
{
namespace blog = boost::log;
namespace keywords = boost::log::keywords;
using boost::locale::translate;
using sev = boost::log::trivial::severity_level;
inline static global_variables global;
void init()
{
const auto log_path{[]
{
fs::path path{helpers::get_env("XDG_STATE_HOME")};
if (path.empty())
{
path = helpers::get_env("HOME");
if (!path.empty())
{
path /= ".local";
path /= "state";
}
}
if (!path.empty())
{
path /= "epubgrep";
}
return path / "epubgrep.log";
}()};
global.textlog = blog::add_file_log(
keywords::file_name = log_path.c_str(),
keywords::format = "%LineID% [%TimeStamp%] "
"[%ThreadID%]: [%Severity%] %Message%");
global.textlog->set_filter(blog::trivial::severity >= sev::info);
blog::add_console_log(std::cerr,
keywords::format = translate("WARNING").str()
+ ": %Message%")
->set_filter(blog::trivial::severity == sev::warning);
blog::add_console_log(std::cerr, keywords::format = translate("ERROR").str()
+ ": %Message%")
->set_filter(blog::trivial::severity == sev::error);
blog::add_console_log(std::cerr,
keywords::format = translate("FATAL ERROR").str()
+ ": %Message%")
->set_filter(blog::trivial::severity == sev::fatal);
blog::add_common_attributes();
}
void enable_debug()
{
global.textlog->set_filter(blog::trivial::severity >= sev::debug);
blog::add_console_log(std::cerr,
keywords::format = "[%Severity%] %Message%")
->set_filter(blog::trivial::severity <= sev::info);
LOG(sev::info) << "Debug logging enabled.";
}
} // namespace epubgrep::log