实现文件
LogUtil.hpp
/**
* 通用日志实现
* lsl
* 2024-06-04
*/
#ifndef LOGUTIL_HPP
#define LOGUTIL_HPP
#include<iostream>
#include <time.h>
#include <cstring>
#define __FILENAME__ (strrchr(__FILE__, '/') ? (strrchr(__FILE__, '/') + 1):__FILE__)
char* __DATETIME__(){ char format[32]="%Y-%m-%d %X";time_t tt = time(NULL);struct tm ltm;localtime_r(&tt, <m);char*s=new char[32];strftime(s, 32, format, <m);return s; };
#define LogInfo(msg) (std::clog<<"["<<__DATETIME__()<<"][INFO]["<<__FILENAME__<<"]["<<__FUNCTION__<<":"<<__LINE__<<"] "<<msg<<std::endl)
#define LogWarn(msg) (std::clog<<"["<<__DATETIME__()<<"][WARN]["<<__FILENAME__<<"]["<<__FUNCTION__<<":"<<__LINE__<<"] "<<msg<<std::endl)
#define LogError(msg) (std::clog<<"["<<__DATETIME__()<<"][ERROR]["<<__FILENAME__<<"]["<<__FUNCTION__<<":"<<__LINE__<<"] "<<msg<<std::endl)
#endif // LOGUTIL_HPP
DATETIME()的实现输出当前的日期时间,只有年月日时分秒,没有毫秒。如果需要毫秒,可以使用下面的方法是实现。
#include <iostream>
#include <chrono>
#include <iomanip>
int main() {
// 获取当前时间点
auto now = std::chrono::system_clock::now();
// 将时间转换为time_t以便进一步转换为tm结构
std::time_t now_time = std::chrono::system_clock::to_time_t(now);
// 转换为tm结构
std::tm* now_tm = std::localtime(&now_time);
// 获取秒和毫秒
int millis = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
// 输出时间和毫秒
std::cout << std::put_time(now_tm, "%Y-%m-%d %H:%M:%S") << '.' << std::setfill('0') << std::setw(3) << millis << std::endl;
return 0;
}
基本功能
三种日志类型,INFO,WARN,ERROR
日志携带日期时间
日志携带文件名、函数名和日志所在行。
测试
prog1.cc
#include<LogUtil.hpp>
int main(){
LogInfo("测试"<<11<<"hahah ");
LogWarn("测试2"<<11<<"hahah ");
LogError("测试3"<<11<<"hahah ");
return 0;
}
编译
g++ prog1.cc LogUtil.hpp -I./ -o logutil
运行
./logutil &>log_20240604.log
[root@localhost myPractice]# ./logutil &>log_20240604.log
[root@localhost myPractice]# cat log_20240604.log
[2024-06-04 18:02:01][INFO][prog1.cc][main:3] 测试11hahah
[2024-06-04 18:02:01][WARN][prog1.cc][main:4] 测试211hahah
[2024-06-04 18:02:01][ERROR][prog1.cc][main:5] 测试311hahah
额外知识点
- main函数是int类型,return 0说明程序正常退出。 通过命令 echo &? 能查看到退出情况。
- 重定向 < 输入,对应cin, 标准输出1>,对应cout, 错误输出2>,对应cerr,clog。
- 1>>tt.log 追加输出, 2>>tt.log, &>>tt.log 所有追加输出到一个文件。