LoginSignup
0
0

More than 3 years have passed since last update.

log4cppでログ出力

Last updated at Posted at 2019-04-22

はじめに

Javaのlog4j的なものがC++でもないかと探していたところ、似たようなライブラリを見つけたので、使ってみる。

ソースコード

ロガークラスを作成する。

Logger.h
#pragma once
#include <log4cpp/Category.hh>
#include <log4cpp/PropertyConfigurator.hh>

class Logger
{
public:
    Logger();
    ~Logger();
    static bool initLogger(const char*);
    static log4cpp::Category& getLogger(const char*);
};
Logger.cpp
#include "Logger.hpp"

Logger::Logger() {}

Logger::~Logger() {}

bool Logger::initLogger(const char *confName) {
  try {
    log4cpp::PropertyConfigurator::configure("logging.conf");
    return true;
  } catch (log4cpp::ConfigureFailure &ex) {
    std::cout << "Error conf is not exists\n";
    return false;
  }
}

log4cpp::Category &Logger::getLogger(const char *categoryName) {
  return log4cpp::Category::getInstance(categoryName);
}
logging.conf
# カテゴリの設定
log4cpp.rootCategory=INFO, rootAppender

# アペンダの設定
log4cpp.appender.rootAppender=FileAppender
log4cpp.appender.rootAppender.fileName=sample.log
log4cpp.appender.rootAppender.layout=PatternLayout
log4cpp.appender.rootAppender.layout.ConversionPattern=[%d %p %c] %m%n
main.cpp
#include "Logger.hpp"

int main() {
  Logger::initLogger("logging.conf");
  log4cpp::Category &logger = Logger::getLogger("sample");
  logger.info("hello");
}

ビルド/実行

Logger_sample.png

参考

http://www.02.246.ne.jp/~torutk/cxx/log4cpp/log4cpp.html
https://www.techscore.com/tech/Java/ApacheJakarta/Log4J/1

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0