log4net在独立Task中停止工作问题求助
Looks like you're hitting a common gotcha with log4net in Windows Services: logs from the main thread work fine, but logs inside Task.Factory.StartNew() vanish completely—even though the exact same code runs perfectly in a console app. Let's break down the most likely causes and fixes:
1. Ensure Explicit log4net Initialization in Windows Service
Windows Services have a different startup lifecycle than console apps, and implicit initialization (like using the [assembly: XmlConfigurator] attribute) might not properly propagate configuration to background threads.
- Fix: Initialize log4net explicitly in your service's
OnStartmethod, making sure it loads the config before any background tasks run:protected override void OnStart(string[] args) { // Load log4net config from your service's App.config var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App.config"); log4net.Config.XmlConfigurator.Configure(new FileInfo(configPath)); Logger.Info("Service started, log4net initialized successfully"); // Kick off your business logic here } - Also, double-check that your
Loggerinstance is a static singleton (e.g.,private static readonly ILog Logger = LogManager.GetLogger(typeof(YourServiceClass));). Creating new Logger instances per thread can lead to missing config.
2. Verify Windows Service Permissions
Windows Services often run under restricted accounts (like Local System), and while the main thread might temporarily have write access to ${PROGRAMDATA}\DEVIT\eProc\, background threads might not.
- Fix:
- Right-click your Windows Service → Properties → Log On tab → Select an account with Modify/Write permissions to the log directory. A local admin account or dedicated service account works best.
- Manually validate directory permissions: Right-click
${PROGRAMDATA}\DEVIT\eProc\→ Properties → Security → Confirm the service's account has the necessary write access.
3. Tweak log4net Appender Configuration
Your RollingFileAppender has a couple of settings that could cause issues with background thread logging:
- The
DatePatternformat uses hardcoded quotes around the filename, which might cause unexpected rolling behavior. Ensure you're using the correct pattern syntax, and explicitly set the rolling style:<appender name="InfoLog" type="log4net.Appender.RollingFileAppender"> <!-- ... existing settings ... --> <rollingStyle value="Date" /> <!-- Explicitly set rolling to date-based --> <datePattern value="yyyy-MM-dd'_CadRmsSyncService_Info.log'" /> <!-- Adjust pattern if daily rolling is needed --> </appender> - As a quick test, try fetching the Logger instance inside the Task instead of using the shared instance. This ensures the thread picks up the latest log4net configuration:
Task.Factory.StartNew(() => { var threadLogger = LogManager.GetLogger(typeof(YourServiceClass)); string tableName = "PR5600"; threadLogger.Info($"Starting execution of {tableName}"); });
4. Enable log4net Internal Debugging
If the above fixes don't work, enable log4net's internal debug logging to see exactly what's happening with background thread logs:
- Add this to your App.config:
<configuration> <appSettings> <add key="log4net.Internal.Debug" value="true" /> </appSettings> <system.diagnostics> <trace autoflush="true"> <listeners> <add name="log4netDebugListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="C:\temp\log4net_debug.log" /> </listeners> </trace> </system.diagnostics> </configuration> - Run the service, then check
C:\temp\log4net_debug.log—it will detail every log request, including whether background thread logs are being processed, and any file write errors that might be occurring.
内容的提问来源于stack exchange,提问作者Hiren Desai

