在 C# 中获取 log4net 日志文件

发布于 2024-08-03 08:23:48 字数 822 浏览 3 评论 0原文

这是我的 log4net 配置:

<log4net>
    <appender name="MyLogger" type="log4net.Appender.RollingFileAppender">
        <file value="MyLog.log" />
        <appendToFile value="true" /> 
        <rollingStyle value="Size"/>
        <maxSizeRollBackups value="20"/>
        <maximumFileSize value="1000KB"/>
        <layout type="log4net.Layout.PatternLayout">
            <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss},%p,%m%n" />
        </layout>
    </appender>
    <root>
        <level value="DEBUG" />
        <appender-ref ref="MyLogger" />
    </root>
</log4net>

在 C# 中,我试图获取日志文件的名称(MyLog.log)。我用谷歌搜索并尝试了很多东西,但都失败了。有什么帮助吗?

谢谢!

This is my configuration for log4net:

<log4net>
    <appender name="MyLogger" type="log4net.Appender.RollingFileAppender">
        <file value="MyLog.log" />
        <appendToFile value="true" /> 
        <rollingStyle value="Size"/>
        <maxSizeRollBackups value="20"/>
        <maximumFileSize value="1000KB"/>
        <layout type="log4net.Layout.PatternLayout">
            <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss},%p,%m%n" />
        </layout>
    </appender>
    <root>
        <level value="DEBUG" />
        <appender-ref ref="MyLogger" />
    </root>
</log4net>

In C# I'm trying to get the name of the log file (which is MyLog.log). I googled and tried many things but failed to do so. Any help?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

橙味迷妹 2024-08-10 08:23:48

根据您的情况,解决方案非常简单;只需使用这段代码:

var rootAppender = ((Hierarchy)LogManager.GetRepository())
                                         .Root.Appenders.OfType<FileAppender>()
                                         .FirstOrDefault();

string filename = rootAppender != null ? rootAppender.File : string.Empty;

Solution is quite easy in your situation; just use this code:

var rootAppender = ((Hierarchy)LogManager.GetRepository())
                                         .Root.Appenders.OfType<FileAppender>()
                                         .FirstOrDefault();

string filename = rootAppender != null ? rootAppender.File : string.Empty;
一笑百媚生 2024-08-10 08:23:48

当有多个文件追加器时,您可能希望通过名称获取它们。另外,为了确保即使根节点没有引用它,也能获取附加程序,以下代码会有所帮助:

public static string GetLogFileName(string name)
{
     var rootAppender = LogManager.GetRepository()
                                  .GetAppenders()
                                  .OfType<FileAppender>()
                                  .FirstOrDefault(fa => fa.Name == name);

     return rootAppender != null ? rootAppender.File : string.Empty;
}

When having multiple file appenders, you might want to get them by name. Also to make sure to get the appender even if it is not referenced by the root node, the following code helps:

public static string GetLogFileName(string name)
{
     var rootAppender = LogManager.GetRepository()
                                  .GetAppenders()
                                  .OfType<FileAppender>()
                                  .FirstOrDefault(fa => fa.Name == name);

     return rootAppender != null ? rootAppender.File : string.Empty;
}
云淡月浅 2024-08-10 08:23:48

由于我已经在类中定义了一个记录器,所以我只是使用了它。需要注意的一件事是,可能有多个附加程序,并且通常第一个附加程序是控制台(它没有文件)。这是我的解决方案的价值。

using log4net;
using log4net.Appender;
using log4net.Repository;

namespace MyNameSpace {
public class MyClass {

    private static readonly ILog logger = LogManager.GetLogger(typeof(MyClass));

    public String GetLogFileName() {

        String filename = null;

        IAppender[] appenders = logger.Logger.Repository.GetAppenders();
        // Check each appender this logger has
        foreach (IAppender appender in appenders) {
            Type t = appender.GetType();
            // Get the file name from the first FileAppender found and return
            if (t.Equals(typeof(FileAppender)) || t.Equals(typeof(RollingFileAppender))) {
                filename = ((FileAppender)appender).File;
                break;
            }
        }
        return filename;
    }
}

}

Since I already had a logger defined in the class I just used it. One thing to be aware of is that there may be more than one appender and often the first one is the console (which doesn't have a file). Here is my solution for what its worth.

using log4net;
using log4net.Appender;
using log4net.Repository;

namespace MyNameSpace {
public class MyClass {

    private static readonly ILog logger = LogManager.GetLogger(typeof(MyClass));

    public String GetLogFileName() {

        String filename = null;

        IAppender[] appenders = logger.Logger.Repository.GetAppenders();
        // Check each appender this logger has
        foreach (IAppender appender in appenders) {
            Type t = appender.GetType();
            // Get the file name from the first FileAppender found and return
            if (t.Equals(typeof(FileAppender)) || t.Equals(typeof(RollingFileAppender))) {
                filename = ((FileAppender)appender).File;
                break;
            }
        }
        return filename;
    }
}

}

睫毛溺水了 2024-08-10 08:23:48
        String filename = null;

        Hierarchy hierarchy = LogManager.GetRepository() as Hierarchy;
        Logger logger = hierarchy.Root;

        IAppender[] appenders = logger.Repository.GetAppenders();

        // Check each appender this logger has
        foreach (IAppender appender in appenders)
        {
            Type t = appender.GetType();
            // Get the file name from the first FileAppender found and return
            if (t.Equals(typeof(FileAppender)) || t.Equals(typeof(RollingFileAppender)))
            {
                filename = ((FileAppender)appender).File;
                break;
            }
        }

        System.Diagnostics.Process.Start(filename); //for example, open file in notepad
        String filename = null;

        Hierarchy hierarchy = LogManager.GetRepository() as Hierarchy;
        Logger logger = hierarchy.Root;

        IAppender[] appenders = logger.Repository.GetAppenders();

        // Check each appender this logger has
        foreach (IAppender appender in appenders)
        {
            Type t = appender.GetType();
            // Get the file name from the first FileAppender found and return
            if (t.Equals(typeof(FileAppender)) || t.Equals(typeof(RollingFileAppender)))
            {
                filename = ((FileAppender)appender).File;
                break;
            }
        }

        System.Diagnostics.Process.Start(filename); //for example, open file in notepad
沉默的熊 2024-08-10 08:23:48
((log4net.Appender.FileAppender)(_log.Logger.Repository.GetAppenders())[0]).File
((log4net.Appender.FileAppender)(_log.Logger.Repository.GetAppenders())[0]).File
很酷又爱笑 2024-08-10 08:23:48

如果您的配置没有;节点,那么上述解决方案将不适合你。请继续阅读。

<log4net>
  <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="${LOCALAPPDATA}\Anonymous.log" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="10" />
    <maximumFileSize value="2000KB" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    </layout>
  </appender>
  <logger name="AnonymousLog">
    <level value="All" />
    <appender-ref ref="RollingFileAppender" />
  </logger>
</log4net>

这将检索日志文件:(

string path = (LogManager.GetCurrentLoggers()[0].Logger.Repository.GetAppenders()[0] as FileAppender).File;

希望)防崩溃版本:

string path = null;
if (LogManager.GetCurrentLoggers().Length > 0 && LogManager.GetCurrentLoggers()[0].Logger.Repository.GetAppenders().Length > 0)
{
    path = (LogManager.GetCurrentLoggers()[0].Logger.Repository.GetAppenders()[0] as FileAppender).File;
}

最后,如果您遇到 log4net 问题,请将其添加到您的中。部分:

<add key="log4net.Internal.Debug" value="true"/>

If your config does not have a <root> node then the above solution will not work for you. Read on.

<log4net>
  <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="${LOCALAPPDATA}\Anonymous.log" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="10" />
    <maximumFileSize value="2000KB" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    </layout>
  </appender>
  <logger name="AnonymousLog">
    <level value="All" />
    <appender-ref ref="RollingFileAppender" />
  </logger>
</log4net>

This retrieves the log file:

string path = (LogManager.GetCurrentLoggers()[0].Logger.Repository.GetAppenders()[0] as FileAppender).File;

The (hopefully) crash-proof version:

string path = null;
if (LogManager.GetCurrentLoggers().Length > 0 && LogManager.GetCurrentLoggers()[0].Logger.Repository.GetAppenders().Length > 0)
{
    path = (LogManager.GetCurrentLoggers()[0].Logger.Repository.GetAppenders()[0] as FileAppender).File;
}

Finally, if you get stuck with log4net add this to your <appSettings> section:

<add key="log4net.Internal.Debug" value="true"/>
二手情话 2024-08-10 08:23:48

我没有发现上面的代码有效。
这对我有用

var filename= ((log4net.Appender.FileAppender)(((log4net.Appender.IAppender[])((((((log4net.Repository.Hierarchy.Hierarchy)((((log4net.Core.LoggerWrapperImpl)(log)).Logger).Repository)).Root).Hierarchy.Root).Appenders).SyncRoot))[0])).File

I didn't find the above code working.
This worked for me

var filename= ((log4net.Appender.FileAppender)(((log4net.Appender.IAppender[])((((((log4net.Repository.Hierarchy.Hierarchy)((((log4net.Core.LoggerWrapperImpl)(log)).Logger).Repository)).Root).Hierarchy.Root).Appenders).SyncRoot))[0])).File
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文