serilog / serilog-sinks-console

Write log events to System.Console as text or JSON, with ANSI theme support
Apache License 2.0
248 stars 72 forks source link

Coloured DllImport console #117

Closed grounzero closed 2 years ago

grounzero commented 3 years ago

Serilog.Sinks.Console 4.0.0 net5.0-windows

When creating a console in a net5 winforms app using DllImport, and setting applyThemeToRedirectedOutput: true, instead of a coloured console it outputs something this like this before each log.

←[38;5;0242m[←[0m←[38;5;0246m22:43:03←[0m←[38;5;0242m ←[0m←[37;1mINF←[0m←[38;5;0242m] ←[0m←[3

Is there a workaround?

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();
static readonly Logger? Log = new LoggerConfiguration()
    .Enrich.FromLogContext()
    .WriteTo.Console(theme: AnsiConsoleTheme.Code, applyThemeToRedirectedOutput: true)
    .CreateLogger();
grounzero commented 3 years ago

If I call AllocConsole in Program.cs it works as expected regardless of whether I set applyThemeToRedirectedOutput to true or false

nblumhardt commented 3 years ago

Hi! The console needs to be allocated before this is called:

https://github.com/serilog/serilog-sinks-console/blob/dev/src/Serilog.Sinks.Console/Sinks/SystemConsole/ConsoleSink.cs#L37

You can work around it by using a non-ANSI theme, e.g. SystemConsoleTheme.*. HTH!