1:新建项目,如控制台程序
2:Install-Package log4net,详细步骤如下
3:等待上面安装完成后, 新建一个配置文件,log4net.config配置方法同成web.config或app.config一致,并将新建的配置文件里面的内容替换掉为以下代码;
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <!--日志路径--> <param name= "File" value= "D:\App_Log\"/> <!--是否是向文件中追加日志--> <param name= "AppendToFile" value= "true"/> <!--log保留天数--> <param name= "MaxSizeRollBackups" value= "10"/> <!--日志文件名是否是固定不变的--> <param name= "StaticLogFileName" value= "false"/> <!--日志文件名格式为:2008-08-31.log--> <param name= "DatePattern" value= "yyyy-MM-dd".log""/> <!--日志根据日期滚动--> <param name= "RollingStyle" value= "Date"/> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n %loggername" /> </layout> </appender> <!-- 控制台前台显示日志 --> <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender"> <mapping> <level value="ERROR" /> <foreColor value="Red, HighIntensity" /> </mapping> <mapping> <level value="Info" /> <foreColor value="Green" /> </mapping> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%n%date{HH:mm:ss,fff} [%-5level] %m" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="Info" /> <param name="LevelMax" value="Fatal" /> </filter> </appender> <root> <!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) --> <level value="all" /> <appender-ref ref="ColoredConsoleAppender"/> <appender-ref ref="RollingLogFileAppender"/> </root> </log4net> </configuration>
4:在后台代码即C#代码中输入以下内容
static void Main(string[] args) { InitLog4Net(); var logger = LogManager.GetLogger(typeof(Program)); logger.Info("消息"); logger.Warn("警告"); logger.Error("异常"); logger.Fatal("错误"); Console.ReadLine(); } private static void InitLog4Net() {
//AppDomain.CurrentDomain.BaseDirectory的路径为新建的配置文件里配置的路径D:\App_Log\,日志文件名为当前日期,且文件目录即文件会自动创建
var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"); XmlConfigurator.ConfigureAndWatch(logCfg);
}
demo地址:http://pan.baidu.com/s/1i5I8fid 密码:tn9m
更多精彩分享,可关注我的微信公众号:
欢迎观看我的CSDN学院录制的课程:http://edu.csdn.net/lecturer/944