epubgrep/src/log.cpp

85 lines
3.1 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
{
using sev = boost::log::trivial::severity_level;
void init()
{
namespace keywords = boost::log::keywords;
using boost::locale::translate;
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())
{
return (path /= "epubgrep") /= "epubgrep.log";
}
return fs::path{};
}()};
boost::log::add_file_log(keywords::file_name = log_path.c_str(),
keywords::format =
"%LineID% [%TimeStamp%] "
"[%ThreadID%]: [%Severity%] %Message%");
boost::log::add_console_log(std::cerr,
keywords::format = translate("WARNING").str()
+ ": %Message%")
->set_filter(boost::log::trivial::severity == sev::warning);
boost::log::add_console_log(std::cerr,
keywords::format = translate("ERROR").str()
+ ": %Message%")
->set_filter(boost::log::trivial::severity == sev::error);
boost::log::add_console_log(std::cerr,
keywords::format = translate("FATAL ERROR")
.str()
+ ": %Message%")
->set_filter(boost::log::trivial::severity == sev::fatal);
boost::log::add_common_attributes();
}
} // namespace epubgrep::log