App.Config文件
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="%property[LogFileName]"/>
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<appendToFile value="true"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="10000"/>
<maximumFileSize value="10MB"/>
<staticLogFileName value="true"/>
<layout type="log4net.Layout.PatternLayout">
<param name="CoversionPattern" value="%date [%thread] : %message%newline%exception"/>
</layout>
</appender>
<root>
<level value="ALL"></level>
<appender-ref ref="LogFileAppender"/>
</root>
</log4net>
我在assemblyinfo.cs中添加了
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
app.config中的错误是什么我没有得到日志文件,并且在写日志文件时也没有收到任何错误。这是Windows应用程序。
我在Bin文件夹中搜索文件是否正确?
答案 0 :(得分:1)
更改app.config行:
<file type="log4net.Util.PatternString" value="%property[LogFileName]"/>
到这个
<file type="log4net.Util.PatternString" value=".\%property{LogFileName}" />
然后确保在globalcontext中设置logFilename,示例代码如下所示:
static void Main(string[] args)
{
log4net.GlobalContext.Properties["LogFileName"] = "log.txt";
log4net.ILog logger = log4net.LogManager.GetLogger("Tests");
logger.Debug("Test message");
}
有关详细信息,请参阅此处:https://www.codeproject.com/Tips/400224/Multiple-log-files-from-one-application-using-log
根据构建配置 - 调试/发布,您应该在BIN / debug或BIN / release文件夹中看到log.txt。
答案 1 :(得分:1)
配置中有2个错误:
变化:
<param name="CoversionPattern" value="%date [%thread] : %message%newline%exception"/>
TO:
<conversionPattern value="%date{ABSOLUTE} [%logger] %level - %message%newline%exception"/>
和
变化:
<file type="log4net.Util.PatternString" value="%property[LogFileName]"/>
TO:
<file type="log4net.Util.PatternString" value="C:\MyLogs\%property{LogFileName}.txt"/>
必须在大括号内直接指定查找的键 遵循模式说明符,例如%属性{用户}
总工作appender配置:
<appender name="RollingFileAppender" type="log4net.appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="C:\MyLogs\%property{LogFileName}.txt"/>
<appendToFile value="true"/>
<rollingStyle value="Size"/>
<maximumFileSize value="10MB"/>
<maxSizeRollBackups value="5"/>
<staticLogFileName value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{ABSOLUTE} [%logger] %level - %message%newline%exception"/>
</layout>
</appender>
和c#代码:
using System;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace Log4NetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
log4net.GlobalContext.Properties["LogFileName"] = "log";
log4net.ILog log = LogHelper.GetLogger();
Console.WriteLine("hello world");
log.Error("This is my error message");
Console.ReadLine();
}
}
}