一、C++ 最简单的日志类
1.介绍
因为要求用C++写 “猴子选王” 的题要求日之类,奈何,C++ 我不会使用过框架,干脆写个简单暴力的日志类.
要求性能 请点击左上角(这里是最简单的C++日志类,只求能用)
2. 使用方法
2.1 Log.cpp
在你自己的项目源文件里
添加一个.cpp 文件 取名 “Log.cpp”(注意L是大写)
粘贴以下代码在 “Log.cpp”
#pragma once
#ifndef EASY_LOG_H_8080
#define EASY_LOG_H_8080
#include <ctime>
#include <iostream>
#include <fstream>
#include <direct.h>
using namespace std;
/**
* @Author Deng Jiawen
* @create 2020/9/15 16:41
*/
class Log
{
public:
/**
* type is info for logs.
*/
static void info(std::string log) {
string type = "INFO";
write(log,type);
}
/**
* type is debug for logs.
*/
static void debug(std::string log) {
string type = "DEBUG";
write(log, type);
}
/**
* type is WARNING for logs.
*/
static void warning(std::string log) {
string type = "WARNING";
write(log, type);
}
/**
* type is ERROR for logs.
*/
static void error(std::string log) {
string type = "ERROR";
write(log, type);
}
/**
* type is CRITICAL for logs.
*/
static void critical(std::string log) {
string type = "CRITICAL";
write(log, type);
}
/**
* get timestamp.
*/
static std::string getTimestamp() {
time_t timep;
time(&timep);
char tmp[64];
struct tm nowTime;
localtime_s(&nowTime, &timep);
strftime(tmp, sizeof(tmp), "%Y-%m-%d-%H:%M:%S", &nowTime);
return std::string(tmp);
}
/**
* base method,write log.
*/
static void write(std::string log,std::string type) {
try
{
//this is the log path , you can modify the path if you want.
string filePath = "D:/monkey.log";
std::ofstream ofs;
ofs.open(filePath, std::ofstream::app);
//tiemstamp
ofs <<getTimestamp().c_str() << " - ";
//type of the error.
ofs << "["<< type.c_str() << "] - ";
//this is the log info you want to print.
ofs.write(log.c_str(), log.size());
ofs << std::endl;
ofs.close();
}
catch (...)
{
}
}
};
#endif
2.2 使用
在你想要输出日志的地方添加导入日志类,并添加日志输出
- 1.在你的文件里导入Log.cpp
#include "Log.cpp"
- 2.添加日志输出(info日志举例)
Log::info("info 测试");
举例:
#include<iostream>
#include "Log.cpp"
using namespace std;
int main() {
Log::write("测试3","info");
Log::info("info 测试");
Log::debug("debug 测试");
Log::warning("warning 测试");
Log::error("error 测试");
Log::critical("critical 测试");
return 0;
}
注意:提供的例子类里面有main()方法,可能会和你项目中原有的main()方法冲突,请谨慎使用测试类
2.3 查看日志输出
日志的默认路径是 D:/monkey.log
找到文件位置点击查看
3.拓展 5种日志方法的区别
拓展文字来源https://blog.csdn.net/qwertyuiopasdfgg/article/details/89890945
日志一共分成5个等级,从低到高分别是:
DEBUG
INFO
WARNING
ERROR
CRITICAL
说明:
DEBUG:详细的信息,通常只出现在诊断问题上
INFO:确认一切按预期运行
WARNING:一个迹象表明,一些意想不到的事情发生了,或表明一些问题在不久的将来(例如。磁盘空间低”)。这个软件还能按预期工作。
ERROR:更严重的问题,软件没能执行一些功能
CRITICAL:一个严重的错误,这表明程序本身可能无法继续运行