我需要在本地文件夹中生成日志文件。 我使用以下代码在控制台应用程序中生成日志文件。但是没有创建LogFile。是否需要进行任何更改?
我使用App.Config文件中的以下代码
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<!-- <log4net configSource="log4net.config" /> -->
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="Log4NetApplicationLog.log" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
<layout type="log4net.Layout.PatternLayout">
<param name="Header" value="[Header]\r\n" />
<param name="Footer" value="[Footer]\r\n" />
<param name="ConversionPattern" value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Log4NetApplicationRollingLog.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="FileAppender" />
<appender-ref ref="ConsoleAppender"/>
<appender-ref ref="RollingFileAppender"/>
</root>
</log4net>
<appSettings>
<add key="KeyOne" value="ValueOne"/>
</appSettings>
</configuration>
我将以下文件用于类文件
class Program
{
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
static void Main(string[] args)
{
XmlConfigurator.Configure(); //only once
Log.Debug("Application is starting");
Console.WriteLine("Test Line");
var testClass = new TestClass();
testClass.LogSomething();
Log.Debug("Application is ending");
Console.Read();
}
public class TestClass
{
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public void LogSomething()
{
for (int i = 0; i < 2; i++)
{
Log.InfoFormat("CurrentTime is [{0}]", DateTime.Now.ToString("yyyy.MM.dd-hh.mm.ss~fff"));
}
}
}
}
答案 0 :(得分:2)
我把这个书签放在手边,当我无法让我的日志工作时再回头看它 - 它通常最终会成为一个配置问题......
http://haacked.com/archive/2006/09/27/Log4Net_Troubleshooting.aspx/
基本上,您将此添加到appSettings
<add key="log4net.Internal.Debug" value="true"/>
...然后在</configuration>
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\temp\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
运行您的应用程序,然后转到C:\ temp \ log4net.txt并查看log4net是否抛出任何错误。这通常有助于查明问题的原因。