Skip to content

Switch logging from log4net to Serilog - #4558

Open
Mag-nus wants to merge 1 commit into
ACEmulator:masterfrom
Mag-nus:serilog-switch
Open

Mag-nus wants to merge 1 commit into
ACEmulator:masterfrom
Mag-nus:serilog-switch

Conversation

@Mag-nus

@Mag-nus Mag-nus commented Nov 25, 2026

Copy link
Copy Markdown
Member

Switch logging from log4net to Serilog

Summary

ACE already logs through Microsoft.Extensions.Logging everywhere (#4539, #4553), with a bridge passing every message on to log4net. This PR replaces log4net with Serilog:

  • Serilog is plugged into the existing LogManager.Factory through Serilog.Extensions.Logging. No logging call sites change.
  • Logging is configured in serilog.json instead of log4net.config.
  • An existing log4net.config is converted to serilog.json automatically at startup, so servers keep their logging setup without manual work.
  • log4net, Log4Net.Async and the in-tree log4net bridge are removed, together with the NuGet audit suppression for the log4net advisory (GHSA-4f7c-pmjv-c25w) in eight projects.

Because the messages are already message templates, Serilog keeps their values as structured properties. A sink that understands them (Seq, JSON files, and so on) can filter and search on a player name or GUID.

serilog.json

serilog.json uses Serilog's standard configuration format (Serilog.Settings.Configuration). It follows the same lifecycle log4net.config did:

  1. It is looked for in the working directory, then next to the executable. In a container, a copy in /ace/Config takes precedence.
  2. If it doesn't exist and a log4net.config does (working directory, executable folder, or /ace/Config in a container), the log4net file is converted into serilog.json.
  3. Otherwise serilog.json.example is copied, or serilog.json.docker in a container (also into /ace/Config, as before).

If serilog.json can't be loaded (invalid JSON, or a setting Serilog rejects), the server still starts and logs Information and above to the console only. Its first log message is an error naming the file and the problem.

serilog.json is git-ignored like log4net.config. The build's pre-build step copies it between the project and output folders the same way.

A relative log file path is relative to the executable's folder, as it was with log4net. Serilog on its own resolves relative paths against the working directory, which would move the logs of any server started from another folder, so SerilogSetup resolves them before Serilog reads the config.

The four shipped log4net examples are ported:

log4net Serilog
log4net.config.example serilog.json.example
log4net.config.docker serilog.json.docker
log4net.config.ConsoleExample serilog.json.ConsoleExample
log4net.config.FilesExample serilog.json.FilesExample

The default config is the same as before: everything is logged, Packets at Information and above. The console shows Information and above, the file ACE_Log.txt shows everything and rolls at 20 MB keeping 10 old files. Writing is asynchronous. The two filtering examples use Serilog.Expressions filters in place of log4net's filter chains, and are now also asynchronous (see Performance).

Changes take effect without a restart, for levels

log4net reloaded the whole file when it changed. Serilog reloads the minimum levels (the default and the per-logger overrides) when serilog.json changes, so turning on Debug for a logger still needs no restart. Changes to sinks, filters or output templates need a restart.

Automatic log4net conversion

Logging/Log4NetConfigConverter.cs translates a log4net XML config into serilog.json:

  • Levels: the <root> level, <logger> levels (as MinimumLevel.Override), and the repository threshold.
  • Appenders:
    • Console appenders, including the coloured ones, become the Console sink.
    • FileAppender and RollingFileAppender become the File sink, with file name, size limit, number of kept files, date-based rolling, shared locking and buffering.
    • Forwarding appenders are followed through to the appenders they feed. Async forwarding appenders become Serilog's Async sink.
    • Appender thresholds carry over.
  • Layouts: PatternLayout patterns become output templates, covering date (and its named formats), level, logger, thread, message, newline, exception and properties. SimpleLayout is also supported.
  • Filters: LevelMatchFilter, LevelRangeFilter, StringMatchFilter (text and regex), LoggerMatchFilter and DenyAllFilter become one Serilog.Expressions filter per sink. The filter keeps log4net's rules: filters run in order, the first one to accept or deny decides, and an event nothing decides is accepted.
  • Logger-specific appenders: <logger> elements with their own appenders, including additivity="false" at any depth, are routed by logger name, following log4net's dot-separated hierarchy.
  • %thread is kept exactly: the thread's name, or its id when it has no name ([World Manager], [1]). A small enricher in ACE.Server (WithThread) provides it.

Anything that can't be converted exactly is skipped and logged as a warning when the server starts, for example an SMTP appender, %method in a pattern, or per-level console colours. The warning after a conversion also says that log4net.config is no longer read. The old file is left in place.

If the conversion fails (for example malformed XML), the example config is used and an error says why.

Verified against log4net itself

Outside the repo, a harness ran each log4net config through log4net 2.0.17 with the old bridge, and the converted config through Serilog. Both received the same 210 messages (7 loggers, 5 levels, 6 message shapes), and the lines written to each output were compared.

  • The four shipped configs and a real server config (five appenders, one outside the async forwarder, a regex chat filter) produce identical output.
  • 1,200 randomly generated configs produce identical output. They combine thresholds, all five filter types with every acceptOnMatch setting, nested forwarding and async appenders, logger levels, logger appenders and additivity.
  • Where an output is fed by an async route, line order can differ between the two, as it could between two log4net runs.
  • This found two conversion bugs, both fixed and covered by tests: LevelRangeFilter accepts in-range events outright by default, and a non-additive logger also hides its events from loggers above it.

All 820 distinct log templates in ACE (2,112 placeholders) were also parsed with both Microsoft's and Serilog's parser, and give the same placeholders.

Differences in output

  • Level names are Serilog's three-letter form: INF, WRN, DBG, ERR, FTL instead of INFO , WARN , and so on.
  • Rolled files are named ACE_Log_001.txt, ACE_Log_002.txt, … with the newest file having the highest number. Previously the current file was always ACE_Log.txt and the backups were ACE_Log.txt.1, ACE_Log.txt.2, … Existing .1–.10 backups are not touched or cleaned up.
  • Console colours: Serilog colours the level and the values in each line, not the whole line by level.
  • Null values and collections print as null and [1,2] instead of (null) and 1, 2.
  • Number and date formatting in messages uses the server's culture, because Serilog formats values when it writes them. Use standard ILogger calls everywhere #4553 formatted them with the invariant culture. On an en-US server only dates logged without an explicit format differ.
  • Buffered messages are flushed when the process exits and before it terminates on an unhandled exception. Log4Net.Async dropped whatever was still queued at shutdown.
  • Serilog's own errors are written to standard error. While serilog.json loads, every report is printed, because a misspelled sink or enricher is skipped with nothing else to show for it. Once logging is running, a report is followed by a minute of silence: a failing sink reports every message it loses, so unthrottled this would be a console write per lost message.

Performance

Measured with the old stack (log4net 2.0.17, Log4Net.Async, the bridge) and the new one side by side, Release build, .NET 10, 4 cores.

On the thread that logs (default config: everything on, one async queue):

Message Old New
Constant text 268 ns, 888 B 239 ns, 296 B
Pre-built text ({Message:l}) 274 ns, 1,080 B 273 ns, 352 B
2 values 324 ns, 1,040 B 366 ns, 688 B
5 values 487 ns, 1,192 B 496 ns, 920 B
Level off 53 ns, 96 B 48 ns, 96 B

Time is the same within about 10% either way. Allocation is 23–67% lower, because the message text is no longer built on the calling thread.

Console: Serilog's default console theme writes each part of a line separately with a colour change each time: 57 write calls per line against log4net's 5, and 7 times slower (142 µs against 19 µs per line). The shipped configs and the converter therefore set an ANSI theme, which writes each line once: 2 write calls and 12 µs per line. A plain ConsoleAppender converts to the uncoloured theme, which is also a single write.

Writing a file costs about 20% more per message than log4net (1.46 µs against 1.24 µs). In the default config that is on the background thread.

Filters on message text outside the async sink are the one case that is slower on the calling thread. Serilog builds the message text for each filter that checks it, where log4net received it already built. With five synchronous files and two regex filters (the old FilesExample shape), a message costs 2.6 µs and 2.6 KB against 1.8 µs and 0.5 KB. So:

  • the two shipped filtering examples now wrap their sinks in Async;
  • a converted config stays faithful to the original (synchronous stays synchronous), and logs a warning naming any appender that filters on message text outside an async appender.

Memory: the async queue holds up to 10,000 messages (Serilog's default) against Log4Net.Async's 1,000. At a few hundred bytes each that is under 10 MB at worst, and only while the writer is behind. Both drop messages when the queue is full. Values other than strings and numbers are turned into text when logged, so a queued message never keeps a game object alive.

Template cache: the provider caches up to 1,000 parsed templates. ACE has 820, none built at runtime and none over the 1,024-character cache limit.

Compatibility

  • Server operators don't need to do anything: the first start converts their log4net.config.
  • A mod that references log4net directly will no longer find the assembly. Mods should log through ACE.Common.Logging.LogManager.

Packages

Added to ACE.Server:

  • Serilog 4.4.0
  • Serilog.Extensions.Logging 10.0.0
  • Serilog.Settings.Configuration 10.0.1
  • Serilog.Sinks.Async 2.1.0
  • Serilog.Sinks.Console 6.1.1
  • Serilog.Sinks.File 7.0.0
  • Serilog.Expressions 5.0.0
  • Microsoft.Extensions.Configuration.Json 10.0.15

The versions stay on the .NET 10 line ACE already uses (Microsoft.Extensions.Logging 10.0.15).

Removed: log4net 2.0.17 and Log4Net.Async.Standard 3.1.0. dotnet list package --vulnerable --include-transitive reports no vulnerable packages in any project.

Testing

  • The solution builds with 0 warnings and 0 errors.
  • 38 new tests in ACE.Server.Tests/Logging pass:
    • Through the provider:
      • templates, format specifiers and escaped braces render
      • pre-built text renders literally
      • every level maps to its Serilog level
      • exceptions are attached
      • values aren't formatted when their level is off
      • the logger name becomes SourceContext and overrides apply to it
      • loggers created before the provider is added still receive output
    • Conversion:
      • converting the old default and docker configs gives exactly the new shipped serilog.json.example and serilog.json.docker
      • the old and new versions of all three routing examples (default, console, files) are run with the same messages and send each message to the same outputs
      • logger hierarchy, additivity (including nested), ordered filter chains, the LevelRangeFilter default, console themes, date-pattern file extensions, unsupported appenders and rolling settings each have a test
    • Startup:
      • conversion from the executable folder, the working directory and the container volume
      • an existing serilog.json wins
      • the example and docker files are copied when needed
      • a malformed log4net.config falls back to the example
      • all four shipped example files load
      • relative file paths resolve against the executable folder
      • the thread enricher writes the thread name or id
      • SelfLog prints one report and then goes quiet
      • a level change in serilog.json applies without a restart
  • ACE.Server.Tests (4), ACE.Database.Tests (7) and ACE.DatLoader.Tests (6) fail the same tests as on master, all for environmental reasons. ACE.Adapter.Tests passes.
  • I started the built server from a different working directory, with the old log4net.config.example and no serilog.json. It converted the file, logged the conversion notice to the console and to ACE_Log.txt next to the executable, and wrote an unhandled-exception message to the file before exiting. A second start used the existing serilog.json unchanged.
  • Not tested: a full server run with players, a Docker container start, and anything on Windows. The benchmarks and the console measurements were run on Linux.

Files

  • Source/ACE.Server/Logging/SerilogSetup.cs (new): config file lifecycle, conversion, relative paths, SelfLog, provider setup and flushing
  • Source/ACE.Server/Logging/Log4NetConfigConverter.cs (new)
  • Source/ACE.Server/Logging/ThreadEnricher.cs (new)
  • Source/ACE.Server/Logging/Log4NetBridgeProvider.cs (deleted)
  • Source/ACE.Server/Program.cs: log4net startup replaced; flush on exit and on a terminating exception
  • Source/ACE.Server/Entity/Actions/ActionQueue.cs: the last direct log4net logger, under WRAP_AND_MEASURE_ACT_WITH_STOPWATCH
  • Source/ACE.Server/serilog.json.* (new), Source/ACE.Server/log4net.config.* (deleted)
  • Source/ACE.Server/ACE.Server.csproj: packages, example files, pre-build copy step, audit suppression removed
  • Source/ACE.Common/Logging/LogManager.cs: comments only
  • Source/ACE.Server.Tests/Logging/: SerilogProviderTests.cs, Log4NetConfigConverterTests.cs, SerilogSetupTests.cs and TestData/ (the old log4net configs); LogBridgeTests.cs deleted
  • ACE.Adapter, ACE.Database, ACE.DatLoader and their test projects: log4net audit suppression removed
  • .gitignore: serilog.json
  • .github/dependabot.yml: log4net rule removed

🤖 Generated with Claude Code

Serilog is plugged into the existing LogManager.Factory, so no logging call
sites change. Logging is configured in serilog.json; an existing log4net.config
is converted to it automatically at startup. log4net, Log4Net.Async and the
log4net bridge are removed, along with the log4net audit suppressions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant