IIS 7.5 托管的 WCF 中的 log4net 无写入日志文件

发布于 2024-12-11 12:57:27 字数 5636 浏览 2 评论 0原文

首先,抱歉我的英语不好) 我读过很多关于 log4net 日志记录的文章,但不幸的是我的问题还没有解决...... 我在 IIS 托管的 WCF 服务中通过 log4net 登录时遇到问题。

重要代码的某些部分

我的服务代码部分:

using System;
    [assembly: log4net.Config.XmlConfigurator(Watch = true)]
    namespace Service
    {
        [ServiceBehavior]
        public class MyService : IService
        {
            private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

服务方法的一部分

public string Name()
        {
            log.Info("return name ");
            return "NAME";
        }

这是我的 log4net 文件服务的配置文件

?xml version="1.0"?>
<configuration>
  <!-- Register a section handler for the log4net section -->
  <configSections>
    <section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
  </configSections>
  <appSettings>
    <!-- To enable internal log4net logging specify the following appSettings key -->
    <!-- <add key="log4net.Internal.Debug" value="true"/> -->
  </appSettings>
  <!-- This section contains the log4net configuration settings -->
  <log4net>
    <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
      <file value="log-file.txt"/>
      <appendToFile value="true"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%ndc] ID=%property{EventID} - %message%newline" />
      </layout>
    </appender>
    <!-- Define some output appenders -->
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%ndc] ID=%property{EventID} - %message%newline" />
      </layout>
    </appender>
    <!-- Setup the root category, add the appenders and set the default level -->
    <root>
      <level value="ALL" />
      <appender-ref ref="LogFileAppender" />
      <appender-ref ref="ConsoleAppender" />
    </root>
  </log4net>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

crossdomain.xml
clientaccesspolicy.xml 
Service.svc

已配置并存在于目录中 C:\inetpub\wwwroot 我的服务工作成功,但日志没有写入...

问题: 1) 带有 log4net 配置的配置文件 Service.config 必须位于哪里? 2) 我的Service.dll lib和Service.config位于C:\inetpub\wwwroot\bin。正常吗?

请帮我解决这个问题。 我正在尝试 10 多种登录变体。它们全部都在 WindowsForms 应用程序中工作,但在 IIS 托管的服务中不起作用。 附加信息:当我在服务中调用方法 NAME 时?我尝试通过 File.Create 在当前目录中写入文件并且它可以工作,但是未创建日志文件,我不知道如何解决它。 感谢大家尝试理解我的英语并寻求帮助。)

或者如果您拥有或可以使用 log4net 日志记录创建原始的工作 WCF 服务(可以通过 IIS 发布),请编写此答案代码示例,以便在我的环境中进行测试。

非常感谢。

你好。 谢谢你的回答。 现在我尝试详细描述我的情况以获取更多信息 第一步:我创建新项目。项目类型 - WCF 服务库。 我的服务接口代码是

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace MyService
{
    [ServiceContract]
    public interface IMyService
    {
        [OperationContract]
        string ReturnName();
    }
}

我的服务类是

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyService
{
    public class MyService:IMyService
    {
        public string ReturnName()
        {
            return "Return name";
        }
    }
}

然后我从 Visual Studio 将我的服务发布到 IIS 结果 - 站点目录中的新服务文件 (http://img854.imageshack.us/img854/456/62137541.png)

web.config file for this service is
<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true"/>
  </system.web>
  <system.serviceModel>
    <services>
      <service name="MyService.MyService">
        <endpoint address="" binding="wsHttpBinding" contract="MyService.IMyService">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/Design_Time_Addresses/MyService/Service1/"/>
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

现在,我创建测试控制台应用程序来检查服务。我向控制台应用程序添加服务引用并编写代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TestWCFLog.ServiceReference1;

namespace TestWCFLog
{
    class Program
    {
        static void Main(string[] args)
        {
            MyServiceClient service = new MyServiceClient();
            Console.WriteLine( service.ReturnName());
            Console.ReadLine();
        }
    }
}

,它的工作。 (http://img836.imageshack.us/img836/1718/52151311.png) 现在请告诉我必须添加到我的服务代码和 web.config 文件中的内容? 如何为服务添加 log4net 登录? 我尝试了很多样本​​,但不起作用。 谢谢您的回答。 谢谢。

First of all sorry for my bad english)
I have read a lot of articles about log4net loggining but unfortanly my problem is not resolved yet...
I have a problem with loggining via log4net in WCF services hosted by IIS.

some parts of important code

my service code parts:

using System;
    [assembly: log4net.Config.XmlConfigurator(Watch = true)]
    namespace Service
    {
        [ServiceBehavior]
        public class MyService : IService
        {
            private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

a part of service method

public string Name()
        {
            log.Info("return name ");
            return "NAME";
        }

this is my config file for service for log4net

?xml version="1.0"?>
<configuration>
  <!-- Register a section handler for the log4net section -->
  <configSections>
    <section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
  </configSections>
  <appSettings>
    <!-- To enable internal log4net logging specify the following appSettings key -->
    <!-- <add key="log4net.Internal.Debug" value="true"/> -->
  </appSettings>
  <!-- This section contains the log4net configuration settings -->
  <log4net>
    <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
      <file value="log-file.txt"/>
      <appendToFile value="true"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%ndc] ID=%property{EventID} - %message%newline" />
      </layout>
    </appender>
    <!-- Define some output appenders -->
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%ndc] ID=%property{EventID} - %message%newline" />
      </layout>
    </appender>
    <!-- Setup the root category, add the appenders and set the default level -->
    <root>
      <level value="ALL" />
      <appender-ref ref="LogFileAppender" />
      <appender-ref ref="ConsoleAppender" />
    </root>
  </log4net>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

crossdomain.xml
clientaccesspolicy.xml 
Service.svc

files is configured and present in the directory
C:\inetpub\wwwroot
and my service is work succefuly but log is not writing...

question:
1) where must bee located config file Service.config with log4net configuration?
2) my Service.dll lib and Service.config is located in C:\inetpub\wwwroot\bin. Its normal?

Please help me to resolve this problem.
I'm try more than 10 jther varriants of loggining. All of them is working in WindowsForms Application but not work in service hosted in IIS.
Additional info: when I call method NAME in service? I try to write file in current directory via File.Create and it's work, but loggining file is not created and I dont know how to resolve it.
Thank you all for trying of understanding my English and for help.)

or if you have or can create primitive working WCF service with log4net loggining that is can be published via IIS write in this answers sample of code for my testing on my environment.

A lot of thanks.

Hi.
Thank you for ansver.
Now I try discribe my situation in details for more info
First step: I create new Project. Type of project - WCF service library.
My interface code for service is

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace MyService
{
    [ServiceContract]
    public interface IMyService
    {
        [OperationContract]
        string ReturnName();
    }
}

My class for service is

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyService
{
    public class MyService:IMyService
    {
        public string ReturnName()
        {
            return "Return name";
        }
    }
}

Then I publish from visual studio my service to IIS
as result - new files of service in site directory (http://img854.imageshack.us/img854/456/62137541.png)

web.config file for this service is
<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true"/>
  </system.web>
  <system.serviceModel>
    <services>
      <service name="MyService.MyService">
        <endpoint address="" binding="wsHttpBinding" contract="MyService.IMyService">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/Design_Time_Addresses/MyService/Service1/"/>
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

Now I create test console app for checking service. I add service reference to console app and write code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TestWCFLog.ServiceReference1;

namespace TestWCFLog
{
    class Program
    {
        static void Main(string[] args)
        {
            MyServiceClient service = new MyServiceClient();
            Console.WriteLine( service.ReturnName());
            Console.ReadLine();
        }
    }
}

And it's work. (http://img836.imageshack.us/img836/1718/52151311.png)
Now tell me please what I must add to my service code and to web.config file?
How I can add log4net loginning for service?
I try a lot of samples but it doesnt work.
Thank you for answer.
Thank you.

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

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

发布评论

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

评论(1

囚我心虐我身 2024-12-18 12:57:27

您需要初始化 log4net,并且因为您使用的是 IIS,所以您可以在 Global.asax 文件中执行此操作(如果您还没有一个新文件,请添加一个新文件到您的项目中)。

它应该是这样的:

public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        XmlConfigurator.Configure();

        var logger = LogManager.GetLogger(typeof(Global));

        logger.Info("Starting up services");
    }
}

我还可以在您的配置文件中看到您正在使用旧版 IgnoreSectionHandler。
将您的配置文件更改为:

<configSections>
    <section name="log4net"
      type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>

您的配置文件需要称为 web.config,并且它需要位于您的服务主机文件夹而不是 bin 文件夹下,在您的情况下为 c:\inetpub\wwwroot。

不确定 service.config 是什么意思。当在 IIS 下托管服务时,所有配置都会进入 web.config 文件。

You need to initialise log4net and because you are using IIS you can do it in your Global.asax file(add a new one to your project if you dont have one already).

It should read something like this:

public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        XmlConfigurator.Configure();

        var logger = LogManager.GetLogger(typeof(Global));

        logger.Info("Starting up services");
    }
}

I can also see in your config file that you are using the legacy IgnoreSectionHandler.
change your config file to read like:

<configSections>
    <section name="log4net"
      type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>

your config file needs to be called web.config and it needs to be under your service host folder not bin folder, in your case c:\inetpub\wwwroot.

Not sure what you mean by service.config. When hosting services under IIS all the configuration goes into a web.config file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文