C#写日志类实例
本文实例讲述了c#写日志类,分享给大家供大家参考。
具体实现方法如下:
using system.configuration;
using system.io;
using system.threading;
namespace fqdservice.utils
{
/// <summary>
/// 写日志类
/// </summary>
public class filelogger
{
#region 字段
public static readonly object _lock = new object();
#endregion
#region 写文件
/// <summary>
/// 写文件
/// </summary>
public static void writefile(string log, string path)
{
thread thread = new thread(new parameterizedthreadstart(delegate(object obj)
{
lock (_lock)
{
if (!file.exists(path))
{
using (filestream fs = new filestream(path, filemode.create)) { }
}
using (filestream fs = new filestream(path, filemode.append, fileaccess.write))
{
using (streamwriter sw = new streamwriter(fs))
{
#region 日志内容
string value = string.format(@"{0}
--------------------------------------------------------
{1}
", datetime.now.tostring("yyyy-mm-dd hh:mm:ss"), obj.tostring());
#endregion
sw.writeline(value);
sw.flush();
}
}
}
}));
thread.start(log);
}
#endregion
#region 写日志
/// <summary>
/// 写日志
/// </summary>
public static void writelog(string log)
{
string logpath = configurationmanager.appsettings["logpath"] + "\\fqdservice_log.txt";
writefile(log, logpath);
}
#endregion
#region 写错误日志
/// <summary>
/// 写错误日志
/// </summary>
public static void writeerrorlog(string log)
{
string logpath = configurationmanager.appsettings["logpath"] + "\\fqdservice_errorlog.txt";
writefile(log, logpath);
}
#endregion
}
}
希望本文所述对大家的c#程序设计有所帮助。
上一篇: C# Memcached缓存用法实例详解