当前位置: 移动技术网 > IT编程>开发语言>.net > 一个简单的自定义程序日志小样例

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

荒木纱香,估测胜算,圣者天地

复制代码 代码如下:

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();
}
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网