windows-services - 如何为 c# Windows 服务配置 log4net

标签 windows-services log4net

我有一个 Windows 服务,其中 app.config 文件和 log4net.config 文件是分开的。日志记录不起作用。

在我的 app.config 文件中,我在该部分中有以下内容:

<add key="log4net.Config" value="log4net.config"/>

如果在值中指定 log4net.config 文件的绝对路径,则此方法有效。

我需要提供 log4net.cong 的绝对路径吗? log4net.config 和 app.config 文件与可执行文件位于同一文件夹中。

有任何想法吗?

帕拉格

最佳答案

也许这会有所帮助( Moving your Log4Net configuration out of web.config with ASP.NET 2.0 web sites .)。

以下是您可能感兴趣的部分:

Tell the application to configure log4net using this config file. There are really two spots for this. First, the global.asax and second the assemblyInfo.cs file. Note, that most of the time you will start out with a global.asax file with all of the code inline. For whatever reason, the only way I could get this to work was to break the global.asax up to use a code-behind and then ass the assemblyInfo.cs file. So it ends up looking like this.

global.asax: <%@ Application Language="C#" Inherits="GlobalAsax" %> global.asax.cs (in your App_Code folder):


using System;
using System.Web;

public class GlobalAsax : HttpApplication
{
    // you may have lots of other code here
    void Application_Start(object sender, EventArgs e)
    {
        log4net.Config.XmlConfigurator.Configure();
    }
}

Now that you have your application calling log4net's configuration, you can set an attribute in your assembly info so that log4net knows where to look for the configuration file. AssemblyInfo.cs (in your App_Code folder):

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

The watch flag tells log4net to keep an eye on the configuration file for potential changes. This is helpful if you want to change the configuration from logging everthing to errors only during the middle of your testing.



确保log4net.config总是在那里,将 log4net.config 添加到 csproject,并将其设置为 CopyAlways .它应该出现在调试文件夹中。

您可以使用脚本将所有内容复制到发布文件夹,或者如果您使用的是 MS 安装项目,请手动将该文件添加到项目中。然后将添加一个引用。

关于windows-services - 如何为 c# Windows 服务配置 log4net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1605765/

相关文章:

delphi - Delphi 中的服务应用程序

debugging - 当连接字符串不正确时,Log4Net XmlConfigurator.Configure() 会挂起。 Log4Net 中的错误?

crystal-reports - 部署时出现 Crystal Reports 错误..无法加载文件或程序集“log4net”

c# - 为asp.net MVC3项目配置log4net

log4net - 删除按日期滚动的旧文件

c# - 从 Windows 服务访问环境变量

python - pywin32 Windows 服务不想发送请求状态

c# - 使用来自 Windows 服务的凭据启动进程

c# - 如何自行重启Windows服务C#

logging - log4net - 获取特定于一个记录器的附加程序