为什么 log4net 配置文件代码导致我的 C# Windows 服务无法启动,但代码中实现的相同内容会启动该服务?

Why is the log4net config file code causing my C# Windows service to not start but the same thing implemented in code starts the service?

我在 app.connfig 文件中使用了 log4net 代码,但是服务无法启动。如果我将代码用作单独的 class 并在服务的构造函数中调用它。如果我以后一种方式进行,则不会记录日志。

我的配置文件代码是:-

     <?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
<log4net>
    <appender name="TestAppender" type="log4net.Appender.RollingFileAppender" >
      <file value="C:\log\impersonationlog_JamochaService.log" />
      <encoding value="utf-8" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <!--<rollingStyle value="Size" />
      <maxSizeRollBackups value="5" />
      <maximumFileSize value="5MB" />
      <staticLogFileName value="true" />-->
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %level [%thread] %type.%method - %message%n" />
      </layout>
    </appender>
    <root>
      <level value="All" />
      <!-- If the following line is not included the log file 
      will not be created even if log4net is configured with this file. -->
      <appender-ref ref="TestAppender" />
    </root>
  </log4net>
</configuration>

如果我使用这个 class 而不是 app.config 代码,服务会启动,但日志记录并不总是发生。

public class Logger
    {
        public static void Setup()
        {
            Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();

            PatternLayout patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
            patternLayout.ActivateOptions();

            RollingFileAppender roller = new RollingFileAppender();
            roller.AppendToFile = false;
            roller.File = "C:\Logs\EventLog.txt";
            roller.Layout = patternLayout;
            roller.MaxSizeRollBackups = 5;
            roller.MaximumFileSize = "1GB";
            roller.RollingStyle = RollingFileAppender.RollingMode.Size;
            roller.StaticLogFileName = true;
            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);

            MemoryAppender memory = new MemoryAppender();
            memory.ActivateOptions();
            hierarchy.Root.AddAppender(memory);

            hierarchy.Root.Level = Level.Info;
            hierarchy.Configured = true;
        }
    }

app.config 代码 运行 在向模块添加一些内容后直到昨天下午都表现良好。 class 中的此方法在构造函数中调用,如下所示:-

public Service1()
        {
            InitializeComponent();
            Logger.Setup();
        }

请帮我解决这个问题并重新正确记录数据。

所做的更改是我添加了这段代码并在另一个函数中调用了这个函数,该函数启动了整个服务的默认工作:-

private void SocketCommunication()
            {
                IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);
                permission = new SocketPermission(NetworkAccess.Accept,
                       TransportType.Tcp, "", SocketPermission.AllPorts);
                IPHostEntry ipHost = Dns.GetHostEntry("");
                IPAddress ipAddr = ipHost.AddressList[0];
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 4510);
                socket.Bind(ipEndPoint); //Bind to the client's IP
                socket.Listen(10);//Listen for maximum 10 connections
                sListener = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                Log.Info("Waiting for a client...");
                client = socket.Accept();
                IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
                Log.Info("Connected with " + clientep.Address + " at port " + clientep.Port);

                while (true)
                {


                    //string welcome = "Welcome. "; //This is the data we we'll respond with
                    //byte[] data = new byte[1024];
                    //data = Encoding.ASCII.GetBytes(welcome); //Encode the data
                    //client.Send(data, data.Length, SocketFlags.None); //Send the data to the client
                    //Console.WriteLine("Disconnected from {0}", clientep.Address);



                    byte[] data = new byte[1024];
                    int receivedDataLength = client.Receive(data);
                    string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
                    Log.Info("Data recieved :- " + stringData);

                    //Decode the data received
                    int adder = Convert.ToInt32(stringData);
                    adder++;
                    string input = adder.ToString();
                    data = Encoding.ASCII.GetBytes(input);
                    client.Send(data, data.Length, SocketFlags.None);
                    Log.Info("Data sent :- " + input); //data sent
                }
            }

至于你在 app.config 文件中写的内容,我可以假设你没有添加 configSections 和一个名为 Log4net 的新部分。 因此,您可以做的是进行以下更改以使 Log4net 正常工作。

第一 app.config:

据此进行更改

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<log4net>
<appender name="TestAppender" type="log4net.Appender.RollingFileAppender" >
  <file value="C:\log\impersonationlog_JamochaService.log" />
  <encoding value="utf-8" />
  <appendToFile value="true" />
  <rollingStyle value="Date" />
  <!--<rollingStyle value="Size" />
  <maxSizeRollBackups value="5" />
  <maximumFileSize value="5MB" />
  <staticLogFileName value="true" />-->
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %level [%thread] %type.%method - 
 %message%n" />
  </layout>
  </appender>
  <root>
  <level value="All" />
  <!-- If the following line is not included the log file 
  will not be created even if log4net is configured with this file. -->
  <appender-ref ref="TestAppender" />
</root>
</log4net>
</configuration>

对此:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" 
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"></section>
</configSections>
<startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>  
<log4net>
<appender name="TestAppender" type="log4net.Appender.RollingFileAppender" >
  <file value="C:\log\impersonationlog_JamochaService.log" />
  <encoding value="utf-8" />
  <appendToFile value="true" />
  <rollingStyle value="Date" />
  <!--<rollingStyle value="Size" />
  <maxSizeRollBackups value="5" />
  <maximumFileSize value="5MB" />
  <staticLogFileName value="true" />-->
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %level [%thread] %type.%method - 
%message%n" />
  </layout>
</appender>
<root>
  <level value="All" />
  <!-- If the following line is not included the log file 
  will not be created even if log4net is configured with this file. -->
  <appender-ref ref="TestAppender" />
</root>
</log4net>
</configuration>

然后在要使用的 class 中创建一个 Log4netglobal 对象:

ILog log = LogManager.GetLogger(typeof(yourclassname));

然后在 class 中像这样使用它:

log.info("hi i am a log");

希望对您有所帮助。