windows 下编程实现打印日志

时间:2023-03-08 17:57:39
windows 下编程实现打印日志

下面是在windows下编程实现的日志打印,写的比较简单,可以根据实际情况进行修改使用。

宏WRITELOG在vs2013可以正常使用。

在vs2003和vs2010可能会报错,可以直接使用myLog函数,就是比较麻烦,需要传参数(__FILE__, __FUNCTION__, __LINE__)

这个例子日志会一直保存在同一个文件,如果想要每小时生成一个新的日志文件,请看https://www.cnblogs.com/nanqiang/p/9642231.html

log.h

#pragma once
#define WRITE_LOG_ENABLE //启用日志打印 #include <string>
#include <Windows.h>
#include <stdio.h>
using std::string;
using std::wstring;
extern const char* g_pLogPath; string GetTime();
int myLog(const char* pSourcePath, const char* pFunName, const long lLine, const char* fmt, ...); #ifdef WRITE_LOG_ENABLE
#define WRITELOG(format, ...) myLog(__FILE__, __FUNCTION__, __LINE__, format, ##__VA_ARGS__) #else
#define WRITELOG(format, ...) #endif

log.cpp

#include  "Log.h"
#include "StdAfx.h"
#include <string>
#include <Windows.h>
#include <stdio.h>
using std::string;
using std::wstring; const char* g_pLogPath = ".\\test.log"; string GetTime()
{
SYSTEMTIME st;
::GetLocalTime(&st);
char szTime[] = { };
sprintf(szTime, "%04d-%02d-%02d %02d:%02d:%02d %d ", st.wYear, st.wMonth, st.wDay, st.wHour, \
st.wMinute, st.wSecond, st.wMilliseconds);
return szTime;
}
int myLog(const char* pFileName, const char* pFunName, const long lLine, const char* fmt, ...)
{
int ret = ;
//va_list是一个字符串指针,用于获取不确定个数的参数
va_list args;
//读取可变参数的过程其实就是在堆栈中,使用指针,遍历堆栈段中
//的参数列表,从低地址到高地址一个一个的把参数内容读出来的过程
va_start(args, fmt);
//该函数会根据参数fmt字符串来转换格式并格式化数据,然后将结果输出到参数Stream指定的文件中
//直到出现字符串结束的\0为止。
FILE* fp = NULL;
fp = fopen(g_pLogPath, "a+");
string strTime = GetTime();
fprintf(fp, "%s ", strTime.c_str());//写时间 int nFileNameLen = strlen(pFileName);
char szLine[] = { };
sprintf(szLine, "%ld", lLine);
int nLineLen = strlen(szLine);
int nSpaceLen = - nFileNameLen - nLineLen;
for (int i = ; i < nSpaceLen; ++i)
{
fwrite(" ", , , fp);
}
fprintf(fp, "%s:%ld ", pFileName, lLine);
ret = vfprintf(fp, fmt, args); //获取完所有参数之后,为了避免发生程序瘫痪,需要将 ap指针关闭,其实这个函数相当于将args设置为NULL
va_end(args);
fflush(fp);
fclose(fp);
return ret;
}

main.cpp

// WriteLog.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h"
#include "log.h" int _tmain(int argc, _TCHAR* argv[])
{
for (int i = ; i < ; i++)
{
WRITELOG("打印%s%d%s%\n", "hello...", , "hello...");
}
string test = "结束打印";
WRITELOG("%s\n", test.c_str());
WRITELOG("\n");
// system("pause");
return ;
}