一个简单的自定义程序日志小样例
程序员文章站
2024-03-08 23:19:04
复制代码 代码如下: using system; using system.io; using system.text; public class loginfo { pr...
复制代码 代码如下:
using system;
using system.io;
using system.text;
public class loginfo
{
private string errorinfo_user = ""; // 记录用户自定义错误信息
private string errorposition = ""; // 记录错误的位置信息,可包括类、函数等
private string errorinfo_sys = ""; // 记录系统产生的异常错误信息
// 记录日志信息
public void recorderrorinfo(string position, string error_sys, string error_user)
{
errorposition = position;
errorinfo_sys = error_sys;
errorinfo_user = error_user;
}
// 自定义日志信息格式
private string getlogcontent()
{
string logcontent = "\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";
return logcontent;
}
// 保存日志信息到文件
public void savelogtofile()
{
try
{
// get the file path of the log.
string filename = @"log/loginfo_" + datetime.now.tostring("yyyy-mm-dd") + ".txt";
// get the content of the log.
string logcontent = getlogcontent();
// create the stream of the log file and save the log.
filestream smlog = new filestream(filename, filemode.append, fileaccess.write);
// if the stream is correct.
if (smlog != null)
{
long lfilecontentlen = 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
{ }
}
}
public class logexample
{
private loginfo _log = new loginfo();
// 某处理函数一
public void function_first()
{
try
{
// do something which could be occur exception.
}
catch (exception error)
{
_log.recorderrorinfo("函数function_first", error.message.tostring(), "执行函数function_first时,发生异常!");
_log.savelogtofile();
}
}
// 某处理函数二
public void function_second()
{
try
{
// do something which could be occur exception.
}
catch (exception error)
{
_log.recorderrorinfo("函数function_second", error.message.tostring(), "执行函数function_second时,发生异常!");
_log.savelogtofile();
}
}
}
class program
{
static void main(string[] args)
{
// 创建内建了日志的对象
logexample le = new logexample();
// 执行处理操作一
le.function_first();
// 执行处理操作二
le.function_second();
}
}
上一篇: PHP关键特性之命名空间实例详解
下一篇: java发送邮件示例讲解