1.安装 log4net,通过 Nuget 下载
2.在AssemblyInfo.cs中添加
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "config", Watch = true)]
3.编写log4net.config,放在工程目录和exe目录
<?xml version="1.0"?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/> </configSections> <appSettings> <add key="WebSocketPort" value="45154" /> </appSettings> <log4net> <!--指定日记记录方式,以滚动文件的方式(文件记录)--> <appender name="logInfoToFile" type="log4net.Appender.RollingFileAppender,log4net"> <!--日志路径--> <file value="logs/info"/> <!--是否是向文件中追加日志--> <AppendToFile value="true"/> <!--日志根据日期滚动--> <RollingStyle value="Date"/> <!--日志文件名格式为:info.2021-12-30.txt--> <DatePattern value="'.'yyyy-MM-dd'.txt'"/> <!--日志文件名是否是固定不变的--> <StaticLogFileName value="false"/> <!--布局--> <layout type="log4net.Layout.PatternLayout,log4net"> <ConversionPattern value="%d %-5p [%c] %m%n"/> </layout> </appender> <appender name="logErrorToFile" type="log4net.Appender.RollingFileAppender,log4net"> <file value="logs/error"/> <AppendToFile value="true"/> <RollingStyle value="Date"/> <!--日志文件名格式为:error.2021-12-30.txt--> <DatePattern value="'.'yyyy-MM-dd'.txt'"/> <StaticLogFileName value="false"/> <layout type="log4net.Layout.PatternLayout,log4net"> <ConversionPattern value="%d %-5p [%c] %m%n"/> </layout> </appender> <!-- 根(父)logger --> <root> <!-- 支持级别:ALL --> <level value="ALL" additivity="false"/> <!-- ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF--> <!-- 支持的appender名称:logInfoToFile --> <appender-ref ref="logInfoToFile"/> </root> <!-- logger名称为ApplicationInfoLog,阻止父logger中的appender --> <logger name="ApplicationInfoLog" additivity="false"> <!-- 支持级别:ALL --> <level value="ALL"/> <!-- 支持的appender名称:logInfoToFile --> <appender-ref ref="logInfoToFile"/> </logger> <logger name="ApplicationErrorLog" additivity="false"> <!-- 支持级别:ALL --> <level value="ALL"/> <!-- 支持的appender名称:logErrorToFile --> <appender-ref ref="logErrorToFile"/> </logger> </log4net> </configuration>
4.编写类wLogHelper
public class wLogHelper { public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo"); public static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror"); /// <summary> /// 普通的文件记录日志 /// </summary> /// <param name="info"></param> public static void WriteLog(string info) { if (loginfo.IsInfoEnabled) { loginfo.Info(info); } } /// <summary> /// 错误日志 /// </summary> /// <param name="info"></param> /// <param name="se"></param> public static void WriteLog(string info, Exception se) { if (logerror.IsErrorEnabled) { logerror.Error(info, se); } } }
标签:log4net,info,logerror,static,使用,loginfo,过程,public From: https://www.cnblogs.com/woox/p/17853353.html