簡體   English   中英

Log4net - 不創建日志文件

[英]Log4net - Does not create a log file

我正在使用log4net來創建日志,但它沒有做任何事情。

這是app.config

<?xml version="1.0" encoding="utf-8">
<configuration>
    <configSection>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    </configSection>
    <log4net>
        <appender name="WriteToFile" type="log4net.Appender.FileAppender">
            <file value="log.txt" />
            <layout ="log4net.Layout.SimpleLayout" />
        </appender>
        <root>
            <level value="ALL" />
            <appender-ref ref="WriteToFile"/>
        </root>
    </log4net>
</configuration>

我在AssemblyInfo.cs有以下行:

[assembly: log4net.Config.XmlConfigur(ConfigFile ="App.config", Watch= true)]

這是嘗試寫入文件:

private static readonly ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

public void write()
{
    log.Info("Some text here");
}

並且以下行:

log4net.Config.XmlConfigurator.Configure();

如果這是一個可執行文件,我想你的配置文件在結果bin文件夾中不是App.config ,而是MyApp.exe.config 所以你可以嘗試解決這個問題:

ConfigFile ="App.config"

如果使用默認值,也可以跳過配置文件名:

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

還要確保您運行應用程序的帳戶對您希望寫入日志文件的文件夾具有寫入權限。


更新:

分步指南:

  1. 創建新的控制台應用程序
  2. 安裝log4net NuGet
  3. 在App.config中使用以下內容:

     <?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> <log4net> <appender name="WriteToFile" type="log4net.Appender.FileAppender"> <file value="log.txt" /> <layout type="log4net.Layout.SimpleLayout" /> </appender> <root> <level value="ALL" /> <appender-ref ref="WriteToFile" /> </root> </log4net> </configuration> 
  4. 在你的Program.cs

     using log4net; using System.Reflection; [assembly: log4net.Config.XmlConfigurator(Watch = true)] namespace ConsoleApplication1 { class Program { private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); static void Main(string[] args) { log.Info("Some text here"); } } } 

當我運行靜態Configure方法時,我只使用log4net成功了:

        log4net.Config.XmlConfigurator.Configure();

在下面的一個方法中包裝它讀取應用程序的默認配置,無論是web.config還是app.config:

    private static void InitLogging()
    {
        log4net.Config.XmlConfigurator.Configure();
        _logger = Common.Logging.LogManager.GetLogger(typeof(Program));
        _logger.Debug("Logging initialized");
    }

使用裝飾器屬性看起來更優雅,就像你建議的那樣,但上面提到的值得一試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM