开发一个大系统时,有一个好的日志方案,在调试程序时会有很好的帮助!
下面就是我最近学习总结的一个方法(用 log4net.dll 向文件中添加日志方法)。
1。从 http://logging.apache.org/log4net/ 下载 log4net-1.2.0-beta8.zip,解压 并从
src/log4net.sln加入项目,并生成log4net.dll.
2。 新建一web项目,引入该log4net.dll.
3。新建一LogWritter.config文件,向其中加入以下代码:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender" >
<param name="File" value="d://logfile.log" />
<param name="AppendToFile" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="Header" value="[Header]/r/n"/>
<param name="Footer" value="[Footer]/r/n"/>
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] <%X{auth}> - %m%n" />
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] <%X{auth}> - %m%n" />
</layout>
</appender>
<!-->
<root>
<level value="ALL" />
<appender-ref ref="LogFileAppender" />
</root>
< -->
<logger name="LogWritter">
<level value="ALL" />
<appender-ref ref="LogFileAppender" />
</logger>
</log4net>
</configuration>
4。向项目文件中加入下面的类:
public class LogWritter
{
private static ILog logger=null;
private LogWritter()
{
}
private static void Init()
{
string fileName = "LogWritter.config";
//LogWritter.config文件所在位置
System.IO.FileInfo fi = new System.IO.FileInfo(fileName);
log4net.Config.DOMConfigurator.ConfigureAndWatch(fi);
logger = LogManager.GetLogger("LogWritter");
}
public static void Debug(string str)
{
if(logger == null)
{
LogWritter.Init();
}
logger.Debug (str);
}
public static void Info(string str)
{
if(logger == null)
{
LogWritter.Init();
}
logger.Info(str);
}
public static void Error(string str)
{
if(logger == null)
{
LogWritter.Init();
}
logger.Error(str);
}
}
5。在需要向文件中写入日志时,加上以上类,就可以了
例如;
LogWritter.Debug("web I Debug");
LogWritter.Info("web I Info");
LogWritter.Error("web I Error");
此文档有待进一步完善。有兴趣的同行可以交流一下!