目前比较流行.net的Log框架是log4net,不过个人觉得log4net配置比较繁琐,这里我向大家推荐一个比较简单实用的log框架:NLog。
有兴趣的朋友可以到http://www.nlog-project.org/下载源代码和demo,这里我就不详细介绍了。
我尝试做了一个简单的demo,目的是实现一个简单的日志记录, 愿跟大家一起分享。代码如下:
public class Log
{
Create log instance
Logger logger;
public Log()
{
LogDate = DateTime.Now;
SimpleConfigurator.ConfigureForTargetLogging(GetFileTarget());
logger = LogManager.GetCurrentClassLogger();
}
public void Write(Exception ex)
{
try
{
logger.Info(ex.Message + "\r \n" + ex.StackTrace);
}
catch
{
}
}
public void Write(string message)
{
try
{
logger.Info(message);
}
catch
{
}
}
private string GetLogFile()
{
string fileName = "Log_" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "log", fileName);
}
private FileTarget GetFileTarget()
{
FileTarget ft = new FileTarget();
ft.FileName = GetLogFile();
ft.Layout = "${longdate} ${message}";
ft.KeepFileOpen = false;
ft.Encoding = "iso-8859-2";
ft.OpenFileCacheTimeout = 10;
ft.OpenFileCacheSize = 1;
return ft;
}
private DateTime logDate;
public DateTime LogDate
{
get { return logDate; }
set { logDate = value; }
}
}
{
Create log instance
Logger logger;
public Log()
{
LogDate = DateTime.Now;
SimpleConfigurator.ConfigureForTargetLogging(GetFileTarget());
logger = LogManager.GetCurrentClassLogger();
}
public void Write(Exception ex)
{
try
{
logger.Info(ex.Message + "\r \n" + ex.StackTrace);
}
catch
{
}
}
public void Write(string message)
{
try
{
logger.Info(message);
}
catch
{
}
}
private string GetLogFile()
{
string fileName = "Log_" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "log", fileName);
}
private FileTarget GetFileTarget()
{
FileTarget ft = new FileTarget();
ft.FileName = GetLogFile();
ft.Layout = "${longdate} ${message}";
ft.KeepFileOpen = false;
ft.Encoding = "iso-8859-2";
ft.OpenFileCacheTimeout = 10;
ft.OpenFileCacheSize = 1;
return ft;
}
private DateTime logDate;
public DateTime LogDate
{
get { return logDate; }
set { logDate = value; }
}
}
使用的时候只需要一行代码:
Log.DefaultLog().Write("aaa is ok.");
如果需要记录异常情况,代码如下:
Log.DefaultLog().Write(ex);
源代码下载:/Files/binbin1845/NLogWebTest.rar
http://www.cnblogs.com/binbin1845/archive/2008/04/28/1174791.html
http://www.cnblogs.com/xugang/archive/2008/04/09/1145384.html