日志实现

日志的实现

简介

日志:记录程序日常运行状态。按条记录,记录内容包括:时间、模块、日志级别(致命、出错、警告、信息、调试)、输出位置(文件、终端、系统日志)
格式说明

  • 日志信息格式
yyyy-mm-dd hh-MM-ss [Level] module file:line func:message
日期 + 级别 +模块+ 文件名+行号+函数+具体的信息
  • 日志文件名格式
yyyy-mm-dd-XXXX.log
yyyy-mm-dd-XXXX2.log
  • 接口
级别 详细信息
DEBUG(module,str) 程序的调试信息,最低级
INFO(module,str) 一般要显示的信息,比如登录,退出
ERROR(module,str) 严重错误 主要是程序的错误
WARNING(module,str) 一般警告,比如session丢失
FATAL(module,str) 崩溃,整个程序终止运行
  • 实现思想
    • 打印时间
    • 调用系统的time系列函数设计一个Getcurrenttime()
string Getcurrenttime()
{
    time_t result;
    result = time(NULL);
    char* p=NULL;
    p= asctime(localtime(&result));
    return string(p);
}
  • 打印具体信息的内置宏
作用
FILE 文件名
LINE 行号
func 函数名
  • 日志级别
  • 在不同的地方调用是不一样的,程序开始是调试,程序出错是出错。
  • 输出的位置
  • 默认输出终端
  • 指定路径就输出到指定的路径

简易版小日志

#include<iostream>
#include<cstdlib>
#include<time.h>
#include<cstdio>
#include<cstring>

using namespace std;
//得到当前时间的函数
string Getcurrenttime()
{
  time_t result;
  result = time(NULL);
  char* p=NULL;
  p= asctime(localtime(&result));
  return string(p);
}
//实现两个数相加的函数
long Add(long a,long b)
{
//输出日志模块
  cout<<Getcurrenttime()<<"[调试]"<<"Main"<<"在"<<__FILE__<<"文件中"<<"第"<<__LINE__<<"行的"<<__func__<<"函数中"<<endl;
  return a+b;
}
//主函数:Main函数
int main(int argc,char** argv)
{
//输出日志模块
  cout<<Getcurrenttime()<<"[调试]"<<"Main"<<"在"<<__FILE__<<"文件中"<<"第"<<__LINE__<<"行的"<<__func__<<"函数中"<<endl;
  if(3 != argc) {
      cout << "参数个数错误"<< endl;
      cout << "usage:" << argv[0] << "<数字1> <数字2>" << endl;
      return 1;
  }

  char* end = NULL;
  long a = strtol(argv[1],&end,10);
  if('\0' != *end) {
      cout << "第一个参数格式错误。" << endl;
      cout << "参数应该是整形数字" << endl;
      return 1;
  }

  long b = strtol(argv[2],&end,10);
  if('\0' != *end) {
      cout << "第二个参数格式错误。" << endl;
      cout << "参数应该是整形数字" << endl;
      return 1;
  }
  //调用相加函数
  long c=Add(a,b);
  cout<<c<<endl;
  return 0;

  cout<<"end"<<endl;
}

猜你喜欢

转载自blog.csdn.net/linzetao233/article/details/80228542