dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.8k stars 3.19k forks source link

Colorize LogTo output #23451

Open ajcvickers opened 3 years ago

ajcvickers commented 3 years ago

From an internal discussion with @bricelam: ANSI escape sequences FTW: .LogTo(m => Console.WriteLine("\x1b[1;30m" + m + "\x1b[22;39m"))

A cheatsheet: https://github.com/dotnet/efcore/blob/main/src/ef/AnsiConstants.cs

roji commented 3 years ago

One thing - we should detect whether we're printing to a terminal or not, to avoid outputting ANSI when output is redirected to a pipe or file (e.g. dotnet ef .... > some_file). This is standard Unix behavior which is traditionally done with an isatty check, am hoping that there's something standard for .NET as well...

(is this really about interception?)

roji commented 3 years ago

Maybe this thing?

bricelam commented 3 years ago

IIRC, they added a flag to say whether escape codes are supported (since they weren't until version 1703 of Windows 10). We should use that instead.

ajcvickers commented 3 years ago

@bricelam I think the challenge here is that we don't know where the logs are going. We just send strings to a delegate. So this might have to be a manual opt-in or opt-out.

roji commented 3 years ago

@ajcvickers do you mean it's not possible at the level of dotnet CLI or something? If so that's a serious limitation (is it already tracked?)

ajcvickers commented 3 years ago

I mean just because the application is using a console that supports escape codes doesn't mean that LogTo output is being sent to that console. It might be going to a file, or to an IDE debugging window, or any place else. See examples here: https://docs.microsoft.com/en-us/ef/core/logging-events-diagnostics/simple-logging#directing-the-logs

roji commented 3 years ago

I think that's what Environment.UserInteractive is for. It would be disappointing if .NET didn't have some sort of way to detect this (where Unix had isatty since Roman times).

At some point we should just play around with all these...

bricelam commented 3 years ago

Since we don't know if they'll acutally be using a console, we probably need an opt-in flag. DbContextLoggerOptions.Colorize or someting.

bricelam commented 3 years ago

@roji using Console.IsOutputRedirected is the norm on .NET

bricelam commented 3 years ago

But as Arthur said, they could be sending the message to a COM port and not passing it to Console at all for all we know.