简体   繁体   English

log4net 不工作

[英]log4net not working

Hey I have this configuration in my web.config嘿,我的 web.config 中有这个配置

<log4net>
    <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
        <param name="File" value="mylog.log" />
        <param name="AppendToFile" value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <param name="Header" value="" />
            <param name="Footer" value="" />
            <param name="ConversionPattern" value="%d [%t] %-5p %m%n" />
        </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="%d [%t] %-5p %m%n" />
        </layout>
    </appender>
    <root>
        <level value="DEBUG" />
        <appender-ref ref="LogFileAppender" />
        <appender-ref ref="ConsoleAppender" />
    </root>
</log4net>

but log4net is not working.但 log4net 不起作用。 My project compiles fine, and I get no errors debugging either.我的项目编译得很好,调试也没有错误。 The lines where I tell to log.debug("somemessage") gets run fine, but I can't find the mylog.log file, so where is it?我告诉log.debug("somemessage")的行运行良好,但我找不到mylog.log文件,那么它在哪里?

One gotcha for this type of thing is to make sure to add the XmlConfigurator attribute to the assembly by placing the following line in your AssemblyInfo.cs :这种类型的一个问题是确保将XmlConfigurator属性添加到程序集,方法是在您的AssemblyInfo.cs放置以下行:

[assembly: log4net.Config.XmlConfigurator]

Otherwise log4net never activates.否则 log4net 永远不会激活。

I guess that either log4net is not logging at all, or the file is not ending up where you expect it.我猜想要么 log4net 根本没有记录,要么文件没有在你期望的地方结束。

Firstly, have you actually called首先,你真的打电话给

XmlConfigurator.Configure()

anywhere in your code?在您的代码中的任何地方? If the xml snippet above is in the application configuration file, this call will do the trick.如果上面的 xml 片段在应用程序配置文件中,则此调用将起作用。 If the xml snippet is in it's own file, you'll need to use the .Configure(string) overload that takes the path to the file.如果 xml 片段在它自己的文件中,则需要使用.Configure(string)重载,该重载采用文件路径。 Without this call (or apparently the assembly level attribute mentioned by Kirk Woll), then log4net won't be logging at all.如果没有这个调用(或者显然是 Kirk Woll 提到的程序集级别属性),那么 log4net 将根本不会记录。

If you believe this is all done, and log4net should be logging, then maybe you should put a fully qualified path in for the log file while you debug further.如果您认为这一切都完成了,并且 log4net 应该记录日志,那么也许您应该在进一步调试时为日志文件放置一个完全限定的路径。 That will let you be sure where the file should be.这将使您确定文件应该在哪里。

There is another small gotcha, see here: http://logging.apache.org/log4net/release/manual/configuration.html#dot-config还有另一个小问题,请参见此处: http : //logging.apache.org/log4net/release/manual/configuration.html#dot-config

the [assembly: log4net.Config.XmlConfigurator] method doesn't work with app.config. [assembly: log4net.Config.XmlConfigurator]方法不适用于 app.config。 If you configure log4net from app.config, you must use the log4net.Config.XmlConfigurator.Configure() method.如果从 app.config 配置 log4net,则必须使用log4net.Config.XmlConfigurator.Configure()方法。

Here is my checklist for when log4net is proving to be recalcitrant:这是我在证明 log4net 顽固时的清单:

  • ensure that log4net.config file is copied to the bin\\ folder when building (set to 'Copy if newer' in compiler)确保在构建时将 log4net.config 文件复制到 bin\\ 文件夹(在编译器中设置为“Copy if newer”)
    • when dealing with installed code, ensure that the log4net.config came along for the ride (set to 'Content' in compiler)在处理已安装的代码时,确保 log4net.config 出现(在编译器中设置为“内容”)
  • ensure that the user that the process runs as has write rights to the folder where the logs are to be written确保进程运行的用户对要写入日志的文件夹具有写入权限
  • if in doubt, give promiscuous permissions to c:\\temp\\ and get everything to log to there ()如果有疑问,请向 c:\\temp\\ 授予混杂权限,并将所有内容都记录到那里 ()
  • fire up Sysinternal/Dbgview.exe to see if that tells you anything启动 Sysinternal/Dbgview.exe 看看它是否告诉你什么

For an ASP.NET MVC project adding对于 ASP.NET MVC 项目添加

log4net.Config.XmlConfigurator.Configure();

to the Global.asax.cs also helps:到 Global.asax.cs 也有帮助:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();

        log4net.Config.XmlConfigurator.Configure();
    }
}

These are the steps which eventually got my file logging working:这些是最终使我的文件记录工作的步骤:

  • -Check AssemblyInfo.cs contains the following attribute. -Check AssemblyInfo.cs 包含以下属性。 [assembly: log4net.Config.XmlConfigurator] . [程序集:log4net.Config.XmlConfigurator] This loads log4net.这将加载 log4net。
  • Check the log directory has write permissions.检查日志目录是否有写权限。
  • Check the logger has a format specified.检查记录器是否指定了格式。 This is done by checking each element in your configuration has a layout element specified.这是通过检查配置中的每个元素都指定了一个布局元素来完成的。 Eg:例如:

<appender name="MainLogger"... <layout type="log4net.Layout.SimpleLayout"/>

  • Finally, try turning on log4net internal logging to enable console logging and checking the console.最后,尝试打开 log4net 内部日志记录以启用控制台日志记录并检查控制台。 To do this, add <add key="log4net.Internal.Debug" value="true"/> to your appSettings .为此,请将<add key="log4net.Internal.Debug" value="true"/>到您的appSettings

I've had experiences where logging systems fail silently without raising exceptions.我有过日志系统无声无息地失败而不引发异常的经历。 I suppose this makes sense because if the logger is logging errors then how can it log an error that it's unable to perform logging?我想这是有道理的,因为如果记录器正在记录错误,那么它如何记录无法执行记录的错误?

So if the file isn't created on disk, start by looking into file system permissions to ensure the user your application is running under can write a new file to that disk location.因此,如果该文件不是在磁盘上创建的,请首先查看文件系统权限,以确保运行您的应用程序的用户可以将新文件写入该磁盘位置。

For testing purposes you might want to manually create the file on disk that should be written to and open up permissions for everybody to write to it.出于测试目的,您可能希望在磁盘上手动创建应该写入的文件,并为每个人打开写入权限。 If the logger starts writing to it then you know it's permission based rather than configuration based.如果记录器开始写入它,那么您就知道它是基于权限而不是基于配置的。

On my side, I forgot to mark the config file to be copied while the app is being compiled.在我这边,我忘记在编译应用程序时标记要复制的配置文件。

将配置文件复制到输出目录

Just right click the log4net.config file, select property and then choose Copy to Output Directory to be Copy XXXX只需右键单击log4net.config文件,选择属性,然后选择复制到输出目录即可复制XXXX

Unfortunately none of the above helped.不幸的是,以上都没有帮助。 Explicit configuration in the class to be logged additionaly to the previous settings suggestions did the trick for me.将额外记录到先前设置建议的类中的显式配置对我有用。

string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
log4net.Config.XmlConfigurator.Configure(new FileInfo(assemblyFolder + "/log4net.config"));

I tried all of the above but nothing worked.我尝试了上述所有方法,但没有任何效果。 Adding this line in app.config's configSections section worked for me.app.config 的configSections部分中添加这一行对我configSections

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a" />

Ensure that Version and PublicKeyToken is correct确保VersionPublicKeyToken正确

So, in the Accepted Answer, the solution was to put所以,在接受的答案中,解决方案是把

[assembly: log4net.Config.XmlConfigurator]

into the AssemblyInfo.cs File.进入AssemblyInfo.cs文件。

Also, there was a comment sugesting此外,还有一条评论sugesting

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

however, if it is still not working, consider configuring the name of your log4net config file ( log4net.config in my case):但是,如果它仍然不起作用,请考虑配置您的 log4net 配置文件的名称(在我的情况下为log4net.config ):

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config")]

after that, logging worked like a charm.在那之后,伐木工作就像一个魅力。

<param name="File" value="mylog.log" />

is saying "write mylog.log to actual folder".说的是“将 mylog.log 写入实际文件夹”。 This means that if your webapp is under IIS, then log will be written to C:\\inetpub\\wwwroot\\appname\\mylog.log.这意味着如果您的 webapp 在 IIS 下,那么日志将写入 C:\\inetpub\\wwwroot\\appname\\mylog.log。

If log file is not there, then maybe account under which is app running doesn't have write permission on folder.如果日志文件不存在,那么运行应用程序的帐户可能没有对文件夹的写权限。 You can run Process Monitor from SysInternals to see if and where a file is written.您可以从 SysInternals 运行 Process Monitor 以查看文件是否写入以及写入位置。

Also run VS in debug mode, to see if any exceptions are thrown (Debug->Exceptions->CLR Exceptions, check Thrown).还要在调试模式下运行 VS,以查看是否抛出任何异常(Debug->Exceptions->CLR Exceptions,检查 Thrown)。

In my case I forget to set the log4Net.config file properties as "Content" so the file was not included in the deploy.就我而言,我忘记将 log4Net.config 文件属性设置为“内容”,因此该文件未包含在部署中。 So pay attention on it:所以要注意它:

Compile action : Content

Check your Reporting level is set to "Debug" or "ALL".检查您的报告级别设置为“调试”或“全部”。 This caught me and I spent ages trying to debug my log4net setup.这引起了我的注意,我花了很长时间试图调试我的 log4net 设置。 I had it set to Error and as it wasn't erroring it didn't log anything.我将它设置为 Error 并且因为它没有出错所以没有记录任何内容。

Aside from all the other answers, my problem that was I needed a call to GetLogger() in my start-up class (WinForms example):除了所有其他答案之外,我的问题是我需要在启动类(WinForms 示例)中调用 GetLogger():

static class Program
{
    public static readonly ILog MainLog = LogManager.GetLogger("Main");

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

All my 'meaningful' logging statements were in a DLL that is apparently loaded too late for log4net.我所有的“有意义的”日志语句都在一个 DLL 中,该 DLL 显然为 log4net 加载太晚了。

Also after some hours, I figured out why it wasn't working for me...几个小时后,我想出了为什么它对我不起作用......

i had:我有:

public static class Program
{

    private static CommunicationManager _bcScanner = new CommunicationManager();
    private static ILog _log = LogManager.GetLogger(typeof(Program));
    private static SocketServer socketListener;

but it should be:但它应该是:

public static class Program
    {
        private static ILog _log = LogManager.GetLogger(typeof(Program));
        private static CommunicationManager _bcScanner = new CommunicationManager();
        private static SocketServer socketListener;

So make sure the ILog is on the first line....因此,请确保 ILog 位于第一行....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM