zl程序教程

您现在的位置是:首页 >  工具

当前栏目

一个简单的自定义程序日志小样例

日志程序 简单 一个 自定义
2023-06-13 09:14:11 时间
复制代码代码如下:

usingSystem;
usingSystem.IO;
usingSystem.Text;
publicclassLogInfo
{
privatestringErrorInfo_User="";//记录用户自定义错误信息
privatestringErrorPosition="";//记录错误的位置信息,可包括类、函数等
privatestringErrorInfo_Sys="";//记录系统产生的异常错误信息
//记录日志信息
publicvoidRecordErrorInfo(stringPosition,stringError_Sys,stringError_User)
{
ErrorPosition=Position;
ErrorInfo_Sys=Error_Sys;
ErrorInfo_User=Error_User;
}
//自定义日志信息格式
privatestringGetLogContent()
{
stringLogContent="\r\n--------------------------------------------------------------------------\r\n";
LogContent+="[自定义异常日志]["+DateTime.Now.ToString()+"]\r\n";
LogContent+="=>[Position]=>["+ErrorPosition+"]\r\n";
LogContent+="=>[UserInfo]=>["+ErrorInfo_User+"]\r\n";
LogContent+="=>[SysInfo]=>["+ErrorInfo_Sys+"]\r\n";
LogContent+="--------------------------------------------------------------------------\r\n";
returnLogContent;
}
//保存日志信息到文件
publicvoidSaveLogToFile()
{
try
{
//getthefilepathofthelog.
stringFileName=@"log/LogInfo_"+DateTime.Now.ToString("yyyy-MM-dd")+".txt";
//getthecontentofthelog.
stringLogContent=GetLogContent();
//createthestreamofthelogfileandsavethelog.
FileStreamsmLog=newFileStream(FileName,FileMode.Append,FileAccess.Write);
//ifthestreamiscorrect.
if(smLog!=null)
{
longlFileContentLen=smLog.Length;
smLog.Lock(0,lFileContentLen);
byte[]buffer=Encoding.GetEncoding("gb2312").GetBytes(LogContent);
smLog.Write(buffer,0,buffer.Length);
smLog.Unlock(0,lFileContentLen);
smLog.Flush();
smLog.Close();
}
}
catch
{}
}
}
publicclassLogExample
{
privateLogInfo_Log=newLogInfo();
//某处理函数一
publicvoidFunction_First()
    {
try
{
//dosomethingwhichcouldbeoccurexception.
}
catch(Exceptionerror)
{
_Log.RecordErrorInfo("函数Function_First",error.Message.ToString(),"执行函数Function_First时,发生异常!");
_Log.SaveLogToFile();
}
    }
//某处理函数二
publicvoidFunction_Second()
{
try
{
//dosomethingwhichcouldbeoccurexception.
}
catch(Exceptionerror)
{
_Log.RecordErrorInfo("函数Function_Second",error.Message.ToString(),"执行函数Function_Second时,发生异常!");
_Log.SaveLogToFile();
}
}
}
classProgram
{
staticvoidMain(string[]args)
{
//创建内建了日志的对象
LogExampleLe=newLogExample();
//执行处理操作一
Le.Function_First();
//执行处理操作二
Le.Function_Second();
}
}