serilog / serilog-sinks-console Goto Github PK
View Code? Open in Web Editor NEWWrite log events to System.Console as text or JSON, with ANSI theme support
License: Apache License 2.0
Write log events to System.Console as text or JSON, with ANSI theme support
License: Apache License 2.0
Does this issue relate to a new feature or an existing bug?
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
Describe the solution you'd like
Enable nullable-references in Serilog and add update the codebase to support the nullable reference types in .NET Core 3.0 and 3.1.
Additional context
Links about the *Nullable reference types *:
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
Serilog 2.6.0
Serilog.Sinks.Console 3.1.1
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
Please describe the current behaviour you are experiencing?
Don't know how to configure alternate theme in appsettings.json
This is a documentation issue. There is insufficient documentation on how to change themes via the appsettings.json
. Near the beginning of the README.md
document are listed some theme names: ConsoleTheme.None
, SystemConsoleTheme.Literate
, SystemConsoleTheme.Grayscale
, etc.
However, later when an example JSON configuration is given, none of the above names are used, instead, the example is as follows:
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
Ok, so I'm supposed to prefix the theme name with Serilog.Sinks.SystemConsole.Themes
and change the .
in the theme name to ::
(I guess... - this name mangling is not mentioned in the README.md
) Now I want all colors to be suppressed, which I assume is what the theme named ConsoleTheme.None
does. So I put this in my configuration:
"WriteTo": [
{ "Name": "Console",
"Args": {
"theme": "Serilog.Sinks.SystemConsole.Theme.ConsoleTheme::None, Serilog.Sinks.Console"
}
},
And here's the output from my console app:
Unhandled Exception: System.InvalidCastException: Invalid cast from 'System.String' to 'Serilog.Sinks.SystemConsole.Themes.ConsoleTheme'.
at System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider)
at Serilog.Settings.Configuration.StringArgumentValue.ConvertTo(Type toType)
at Serilog.Settings.Configuration.ConfigurationReader.<>c.<CallConfigurationMethods>b__14_4(<>f__AnonymousType6`2 <>h__TransparentIdentifier0)
at System.Linq.Utilities.<>c__DisplayClass2_0`3.<CombineSelectors>b__0(TSource x)
at System.Linq.Enumerable.SelectListPartitionIterator`2.ToList()
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Serilog.Settings.Configuration.ConfigurationReader.CallConfigurationMethods(ILookup`2 methods, IList`1 configurationMethods, Object receiver)
at Serilog.Configuration.LoggerSettingsConfiguration.Settings(ILoggerSettings settings)
I already read #16 and that didn't help me. Thanks.
Hi there,
Thanks a lot for creating a console logger that uses ansi codes!. One question though, is there a way to specify the theme using appsettings.json?
When using
"WriteTo": [
{ "Name": "Console",
"Args": {
"theme": "AnsiConsoleTheme.Literate",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss zzz}|{Level}|{ThreadId}|{RequestId}|{SourceContext}{NewLine} {Message}{NewLine}{Exception}"
}
}
],
I'm ending with a
Unhandled Exception: System.InvalidCastException: Invalid cast from 'System.String' to 'Serilog.Sinks.SystemConsole.Themes.ConsoleTheme'.
at System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider)
at Serilog.Settings.Configuration.StringArgumentValue.ConvertTo(Type toType)
at Serilog.Settings.Configuration.ConfigurationReader.<>c.<CallConfigurationMethods>b__14_4(<>f__AnonymousType6`2 <>h__TransparentIdentifier0)
at System.Linq.Enumerable.<>c__DisplayClass151_0`3.<CombineSelectors>b__0(TSource x)
at System.Linq.Enumerable.SelectListPartitionIterator`2.ToList()
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Serilog.Settings.Configuration.ConfigurationReader.CallConfigurationMethods(ILookup`2 methods, IList`1 configurationMethods, Object receiver)
at Serilog.Configuration.LoggerSettingsConfiguration.Settings(ILoggerSettings settings)
Best regards,
Jens
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
All, I assume
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
Please describe the current behaviour you are experiencing?
When output template has {Properties:j}
it renders complex types as {..., "$type": "..."}
.
Please describe the expected behaviour if the ?
Instead it should render it without $type
or allow to override that behavior (also in config).
If the current behavior is a bug, please provide the steps to reproduce the issue and if possible a minimal demo of the problem
NOTE: A small code sample goes a long way in expediting bug fixes or illustrating an enhancement you are proposing.
public class HttpRequestInfo
{
public PathString Path { get; set; }
public Dictionary<string, string> QueryString { get; set; }
}
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] <s:{SourceContext}> {Message:lj}{NewLine}{Exception}{NewLine}{Properties:j}{NewLine}")
.CreateLogger();
Log.Logger.ForContext("info", new HttpRequestInfo { Path = "/hello"}, true)
.Error("boom");
output sample:
[20:44:52 ERR] <s:> boom
{"info": {"Path": {"Value": "/hello", "HasValue": true, "$type": "PathString"} "$type": "HttpRequestInfo"}}
A few questions before you begin:
Is this an issue related to the Serilog core project or one of the sinks or community projects. This issue list is intended for Serilog core issues. If this issue relates to a sink or related project, please log on the related repository. Please use Gitter chat and Stack Overflow for discussions and questons.
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
Serilog v2.6.0
Serilog.Sinks.Console v3.1.1
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
Please describe the current behaviour you are experiencing?
I've written a program that is called by an MSBuild agent (our continous integration process with TFS) during the build process.
The output of my program doesn't have any coloration (that's normal because the output is redirected) but there is no outputTemplate (that's the bug)! Even if I force the outputTemplate in the .Console()
at configuration time the output received in the MSBuild Agent only has the message but no timestamp, event type, etc.
I've tried to redirect my program in a console using something like this :
program.exe > outputfile.txt
and the outputfile.txt
has the template!
Do you have any workaround to force the output to be well templated? Or to force to apply the template directly on the message...
Please describe the expected behaviour if the ?
The program output should respect the outputTemplate defined
If the current behavior is a bug, please provide the steps to reproduce the issue and if possible a minimal demo of the problem
NOTE: A small code sample goes a long way in expediting bug fixes or illustrating an enhancement you are proposing.
Well, any chance to separate the coloring functionality to make it work with other sinks, too?
Thanks, OB.
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
latest
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
all
Please describe the current behaviour you are experiencing?
extra method cal or extra zero-length string allocation
Please describe the expected behaviour if the ?
pad > 0 check
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
Serilog.Sinks.Console
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
Linux,
Please describe the current behaviour you are experiencing?
We're sending logs to console, config:
https://gist.github.com/SuddenGunter/3a475c775a7f31fdeb296125a72715f1
Then this output is being collected by gelf and sent to graylog. Config (part of docker-compose.yml):
https://gist.github.com/SuddenGunter/c922d2271242e3777e10696acc66d0d5
log in the middle - log from one of docker containers with asp net core. There was an unhandled exception, 2nd column shows serilog log level as ERROR.
But latest column - is gelf loglevel - and it's always '6' (info) for all logs that came from serilog.
As an example nginx container (lb) shows logs with different log levels, so there must be some issue with our config for serilog, I just could not find it
Please describe the expected behaviour if the ?
Correct mapping of serilog's log levels to gelf log levels
Is it possible to set the console properties from the serilog console sink (for example the window and screen buffer size) ?
Hi,
After quite a few unsuccesful attempts, I have to ask: Is there any way to create a custom format string for use in a single message like this (for console only):
Log.Information("Recieved {Metrics:my-special-format-for-console}.", metrics);
The variable metrics
is a dictionary in this case.
PS. Please let me know if this is not the proper place to ask questions :)
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="log4net" version="2.0.8" targetFramework="net46" />
<package id="Microsoft.AspNet.Razor" version="3.2.7" targetFramework="net46" />
<package id="Newtonsoft.Json" version="11.0.1" targetFramework="net461" />
<package id="RazorEngine" version="3.10.0" targetFramework="net461" />
<package id="Serilog" version="2.9.0" targetFramework="net46" />
<package id="Serilog.Settings.AppSettings" version="2.2.2" targetFramework="net46" />
<package id="Serilog.Sinks.Console" version="3.1.1" targetFramework="net46" />
<package id="Serilog.Sinks.File" version="4.1.0" targetFramework="net46" />
<package id="Serilog.Sinks.RollingFile" version="3.3.0" targetFramework="net46" />
</packages>
Please describe the current behaviour you are experiencing?
I think it is the system environment problem, but I don't know the specific reason.
Please describe the expected behaviour if the ?
If the current behavior is a bug, please provide the steps to reproduce the issue and if possible a minimal demo of the problem
NOTE: A small code sample goes a long way in expediting bug fixes or illustrating an enhancement you are proposing.
<appSettings>
<!--##############################-->
<!--serilog https://github.com/serilog/serilog/wiki/AppSettings
ๆฅๅฟ็บงๅซ Verbose, Debug, Information, Warning, Error, Fatal.-->
<add key="serilog:minimum-level" value="Information" />
<add key="serilog:using:RollingFile" value="Serilog.Sinks.RollingFile" />
<!-- APPDATA TMP -->
<add key="serilog:write-to:RollingFile.pathFormat" value="D:\ๆถๆฏๆฅๅฟๆไปถ\myapplog-{Date}.txt" />
<add key="serilog:write-to:RollingFile.retainedFileCountLimit" value="10" />
<add key="serilog:write-to:File.rollingInterval" value="Minute" />
<add key="serilog:using:Console" value="Serilog.Sinks.Console" />
<add key="serilog:write-to:Console.theme" value="Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console" />
<add key="serilog:write-to:Console.outputTemplate" value="[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} <s:{SourceContext}>{NewLine}{Exception}" />
<!--##############################-->
</appSettings>
private static void Main(string[] args)
{
var logger = new LoggerConfiguration()
.ReadFrom.AppSettings()
.WriteTo.File($"App_Data\\Log\\{DateTime.Now:yyyy\\MMdd}\\่ฟ่กๆฅๅฟlog.txt", rollingInterval: RollingInterval.Minute, retainedFileCountLimit: null)
.CreateLogger();
logger.Information("ๆต่ฏ่พๅบๅๆฐ๏ผ" + (args.Length == 0 ? "ใๆฒกๆๅๆฐใ" : args[0]));
//args = RazorEngineMain(args);
string file = AppDomain.CurrentDomain.BaseDirectory + "Config\\Log4net.config";
XmlConfigurator.Configure(new System.IO.FileInfo(file));
var app = new BaseApplication
{
Name = "็ปไธๆๅก็ปไปถ",
SystemName = "SystemName"
};
Register(app);
app.Execute(args.Length == 0 ? null : args[0]);
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("*********************************");
Console.ForegroundColor = ConsoleColor.Blue;
Console.ReadKey();
Log.CloseAndFlush();
}
Bug
Serilog.Sinks.Console 3.1.1
NET462, Windows 8.1
Please describe the current behaviour you are experiencing?
After try to add custom theme
<add key="serilog:write-to:Console.theme" value="Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console" />
console displays weird characters
Before this change my config was just simple
<add key="serilog:write-to:Console" />
Please describe the expected behaviour if the ?
I'm expecting to see normal console colored output
A few questions before you begin:
Is this an issue related to the Serilog core project or one of the sinks or community projects. This issue list is intended for Serilog core issues. If this issue relates to a sink or related project, please log on the related repository. Please use Gitter chat and Stack Overflow for discussions and questons.
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
3.1.2-dev-00779
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
Please describe the current behaviour you are experiencing?
When running my .NET Core console application colors are suppressed when the streams are redirected.
More importantly, colors in both streams are suppressed even if only one stream is redirected.
E.g.: MyApp.exe > test.txt
redirects stdout (but not stderr) and removes all color from both stdout and stderr.
Please describe the expected behaviour if the ?
Some context: my stdout stream produces data that is usually captured via redirection. Hence I send all logs to stderr and I'd like them to always look the same - whether or not someone is capturing stdout.
If the current behavior is a bug, please provide the steps to reproduce the issue and if possible a minimal demo of the problem
My configuration:
private static IServiceCollection ConfigureLogging(IServiceCollection services)
{
Log.Logger = new LoggerConfiguration()
.Enrich.WithThreadId()
.MinimumLevel.Is(LogEventLevel.Verbose)
.WriteTo.Console(
theme: AnsiConsoleTheme.Literate,
outputTemplate: "{Timestamp:o} [{Level:w5}] <{ThreadId}> {SourceContext} {Message:lj}{NewLine}{Exception}",
standardErrorFromLevel: LogEventLevel.Verbose)
.CreateLogger();
return services.AddLogging(
(configure) =>
{
configure.AddSerilog(Log.Logger, dispose: true);
});
}
And the line in the configuration extension that causes this beaviour:
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.MinimumLevel.Fatal()
.WriteTo.Console(restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Verbose)
.CreateLogger();
Log.Verbose("Starting program.");
This will result in nothing being displayed in the console.
I'm not sure if this should work with .net core 3.0 libraries, but when I try and configure this sink it says it can't be found. I can configure the RollingFile no problem
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Information)
.CreateLogger();
<PackageReference Include="Serilog" Version="2.9.0-dev-01119" />
<PackageRefernece Include="Serilog.Sinks.Console" Version="3.1.2-dev-00806 " />
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
3.1.2-dev-00806
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
Please describe the current behaviour you are experiencing?
Severity Code Description Project File Line Suppression State Error CS1061 'LoggerSinkConfiguration' does not contain a definition for 'Console' and no accessible extension method 'Console' accepting a first argument of type 'LoggerSinkConfiguration' could be found (are you missing a using directive or an assembly reference?)
Please describe the expected behaviour if the ?
If the current behavior is a bug, please provide the steps to reproduce the issue and if possible a minimal demo of the problem
NOTE: A small code sample goes a long way in expediting bug fixes or illustrating an enhancement you are proposing.
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Information)
.CreateLogger();
The StringWriter
created here:
is never disposed Looks like a potential memory leak?
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
All
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
.NET Core 2.0+
Please describe the current behaviour you are experiencing?
When adding this package to a .NET Core 3.1 project, the nearest framework is resolved to netcoreapp1.1
, not netstandard2.0
. As a result, System.Console
, System.Runtime.InteropServices
and System.Runtime.InteropServices.RuntimeInformation
are considered transitive dependencies (and part of the Paket lock file in my case), even though these APIs are available to my taget framework directly by virtue of it implementing netstandard2.0
.
Please describe the expected behaviour if the ?
Expecting Serilog
to be the only transitive dependency for .NET Core 2.0 projects or higher.
Link in Code of Conduct is:
[Serilog Code of Conduct](https://github.com/serilog/serilog/blob/dev/CONTRIBUTING.md)
But should be:
[Serilog Code of Conduct](https://github.com/serilog/serilog/blob/dev/CODE_OF_CONDUCT.md)
I'm having difficulty logging at application start up. The last two lines of my Setup() constructor are:
Log.Logger = loggerConfiguration.CreateLogger();
Log.Information("Inside Startup ctor");
If I log to a file, the message "Inside Startup ctor" appears in the file. If I log to the console using serilog-sinks-console, the message does not appear in the console. Logging inside controllers works perfectly.
Am I doing something wrong? Should this work?
A few questions before you begin:
Is this an issue related to the Serilog core project or one of the sinks or community projects. This issue list is intended for Serilog core issues. If this issue relates to a sink or related project, please log on the related repository. Please use Gitter chat and Stack Overflow for discussions and questons.
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
3.1.1
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
Please describe the current behaviour you are experiencing?
When running two console applications that are the same, just in different directories and config, the second application to start also outputs to the first console application.
Please describe the expected behaviour if the ?
The first console application would not get the second console applications messages.
If the current behavior is a bug, please provide the steps to reproduce the issue and if possible a minimal demo of the problem
Create a console application with a console sink. Create a loop that writes a message to the console.
Copy the console application directory to a new directory.
Run the first console application.
Run the second console application. You will see logging from the second app in both the first and second console app.
NOTE: A small code sample goes a long way in expediting bug fixes or illustrating an enhancement you are proposing.
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
Linux Ubuntu 18.04
Code for 3.0 shown here, but I replicated it in netcoreapp2.2 as well.
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="serilog.sinks.console" Version="3.1.1" />
</ItemGroup>
</Project>
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
Please describe the current behaviour you are experiencing?
log output has no colorization
Please describe the expected behaviour if the ?
colorization of output, as per description
If the current behavior is a bug, please provide the steps to reproduce the issue and if possible a minimal demo of the problem
brand new project, didn't change Startup.cs
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
namespace sinks
{
public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
Log.Error("Hello, world!");
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
launch.json:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"logging": {
"engineLogging": false,
"moduleLoad": false,
"exceptions": true,
"browserStdOut": false,
"programOutput": true
},
"program": "${workspaceFolder}/bin/Debug/netcoreapp3.0/sinks.dll",
"args": [],
"cwd": "${workspaceFolder}",
"stopAtEntry": false,
"serverReadyAction": {
"action": "openExternally",
"pattern": "^\\s*Now listening on:\\s+(https?://\\S+)"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}
Notice that the Serilog log item has no color, however the built-in logger output below it does.
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
Everything above C# 6.
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
Please describe the current behaviour you are experiencing?
When using string interpolation, colors do not show so you're forced to use composite formatting.
Please describe the expected behaviour if the ?
It should color the parameters regardless.
If the current behavior is a bug, please provide the steps to reproduce the issue and if possible a minimal demo of the problem
NOTE: A small code sample goes a long way in expediting bug fixes or illustrating an enhancement you are proposing.
Executing the following produces colors normally:
Log.Information("Hey, {0}, this is a {1}!", parameter1, parameter2);
Executing the following does not produce any colors:
Log.Information($"Hey {parameter1}, this is a {parameter2}!");
I created a customized JSON Formatter which extends ITextFormatter
And try to add it to appsetting.json like this:
"WriteTo": [
{
"Name": "Console",
"Args": {
"formatter": "CustomizedJSONFormatter"
// "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
}
},
The default jsonFormatter works fine as shown in the commented line.
But I will get an error if I want to add the customized one:
InvalidCastException: Invalid cast from 'System.String' to 'Serilog.Formatting.ITextFormatter'.
Is there anyway to solve this?
Thanks!
I would like my program to write machine readable output to stdout and information for humans to stderr. To that end all logging regardless of the log level has to go to stderr and not stdout. How do I configure that?
I am trying to write my own Sink that falls back on all the console stuff but I cant get to classes like these.
A few questions before you begin:
Is this an issue related to the Serilog core project or one of the sinks or community projects. This issue list is intended for Serilog core issues. If this issue relates to a sink or related project, please log on the related repository. Please use Gitter chat and Stack Overflow for discussions and questons.
It is related to this sink (console).
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
NuGet version 3.1.1.
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
Please describe the current behaviour you are experiencing?
When I set "Level" in "outputTemplate" argument to five letter or more, it doesnt format it to provided case. Setting "{Level:u5}" and "{Level:w5}" always format all levels in CamelCase: "Debug", "Infor", etc.
Please describe the expected behaviour if the ?
In case of "{Level:u5}" it should be all upper case and in case of "{Level:w5}" it should be all lower case.
If the current behavior is a bug, please provide the steps to reproduce the issue and if possible a minimal demo of the problem
In JSON configuration
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss,fff} [{ThreadId}] {Level:u5} [{ndc:u8}] usr:{LoggedUser:u10} {Message:lj}{NewLine}{Exception}"
}
}
]
NOTE: A small code sample goes a long way in expediting bug fixes or illustrating an enhancement you are proposing.
Not sure if this is a bug or a limitation. We're using a customized console window in our application for debugging purposes. With VS 2017, Microsoft has done some "debug stdout redirect magic" which broke color output with our console window. We fixed that by changing the color manually based on the logging level as suggested in the links above:
private static void SetForegroundColor(ConsoleColor color)
{
using (var hConsoleOut = new SafeFileHandle(CreateFile(OurCustomConsoleFileHandleName, GenericWrite, FileShareWrite, 0, OpenExisting, 0, 0), true))
{
SetConsoleTextAttribute(hConsoleOut.DangerousGetHandle(), (ushort) color);
}
}
However, when using the console sink, we now don't have any colored output again. I took a look at the ConsoleSink
class, and wrapped the calls in the Emit() method with two SetForegroundColor()
calls that set the color based on the logEvent.Level
and re-set it to the default color after writing the output.
This already worked to my surprise, but I also had to edit the ConsoleLoggerConfigurationExtensions
to use my customized version and add some reflection to deal with the referenced internal classes, which is more of a hack than a proper solution.
Is there something I overlooked in the configuration where I could have changed that without changing the existing sink?
Versions:
System:
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
All of them
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
Please describe the current behaviour you are experiencing?
In wrapping Serilog in one of my projects I stumbled upon the fact that the ConsoleSink
class is not accessible from the outside. Now I personally like this, and would like to keep it hidden from the outside. But I would also like access to the resulting ILogEventSink
. So maybe add a ConsoleSinkFactory that builds the ILogEventSink
var consoleSink = ConsoleSinkFactory.Create()
.With(formatter)
.With(standardErrorFromLevel)
.With(ConsoleTheme.None)
.Build();
According to Open-source library guidance it would be good to target .Net Standard 2.0 to benefit from having a smaller package graph.
I would appreciate to help with it.
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
Serilog.AspNetCore - version 3.1.0
Serilog.Sinks.Console - version 3.1.1
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
Running on windows 10 under IIS, dot net core 2.1.15.
Please describe the current behaviour you are experiencing?
When running my app sometimes my application hangs and stops responding. It's really difficult for me to reproduce. After much debugging I am pretty sure it's the console logger hanging for some reason as I did a memory dump and found 7 threads all sitting on the Serilog.Sinks.Console.dll!Serilog.Sinks.SystemConsole.ConsoleSink.Emit()
method.
Removing the
.WriteTo.Console()
line shown below 'fixed' the problem.
Please describe the expected behaviour if the ?
Not hanging :)
If the current behavior is a bug, please provide the steps to reproduce the issue and if possible a minimal demo of the problem
NOTE: A small code sample goes a long way in expediting bug fixes or illustrating an enhancement you are proposing.
I am really sorry I can't provide a minimal set of code to reproduce the issue. I am using Serilog.aspnetcore 3.1.0 and Seq, and my startup code looks like this:
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.Seq("serverurl", "apikey",
restrictedToMinimumLevel: LogEventLevel.Verbose)
.MinimumLevel.Verbose()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("System.Net.Http", LogEventLevel.Warning)
.Enrich.With(new LogCleaner())
.CreateLogger();
My log cleaner looks like this:
{
class LogCleaner : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
// these properties are created by asp.net core, we don't want them
logEvent.RemovePropertyIfPresent("ActionId");
logEvent.RemovePropertyIfPresent("ConnectionId");
logEvent.RemovePropertyIfPresent("CorrelationId");
logEvent.RemovePropertyIfPresent("EventId");
logEvent.RemovePropertyIfPresent("RequestId");
logEvent.RemovePropertyIfPresent("SourceContext");
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("MachineName", Environment.MachineName));
}
}
It seems to often happen at machine startup - when Seq is not running. I'm not sure if that's related.
https://ci.appveyor.com/project/serilog/serilog-sinks-console/branch/master
Reporting System.Linq doesn't exist, but the issue can't be fixed on my machine by adding a package reference or anything like it.
Both dev and master; although the latest dev build succeeded, checking it out and attempting to build on my machine produces the same result.
Guessing it's an interaction between our use of <DisableImplicitFrameworkReferences>true</DisableImplicitFrameworkReferences>
and the new/2.0 dotnet tooling.
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
Version 3.1.2-dev-00824
What is the target framework and operating system affected by this issue?
Please describe the current behaviour you are experiencing?
I'am using a custom formatting template which is used correctly when running the app locally.
[SRV] 21:36:42 [1] WRN ConsoleApp1.Program: Hello log
But when executing the app on a RaspberryPi over SSH my template is ignored and a different template is used but also different from the default-template.
20:27:01 1 WRN ConsoleApp1.Program Hello log
Why is this happening?
Please describe the expected behaviour if the ?
The defined custom template should be used, also when running over SSH.
How to reproduce:
class Program
{
static void Main(string[] args)
{
var template = "[SRV] {Timestamp:HH:mm:ss} [{ThreadId}] {Level:u3} {SourceContext}: {Message:lj}{NewLine}{Exception}";
var logger = new LoggerConfiguration()
.Enrich.WithThreadId()
.WriteTo.Console(outputTemplate: template)
.CreateLogger()
.ForContext(typeof(Program));
logger.Warning("Hello log");
}
}
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
N/A
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
All of them. :)
Please describe the current behaviour you are experiencing?
Currently it is not possible to decorate the console sink or the ITextFormatter
used by the console sink. This would greatly assist in scenarios as belabored in serilog/serilog#1148 in which formatting is desired to be different in scalar/text-based sinks vs. structure-based sinks.
Please describe the expected behaviour if the ?
Is that a complete sentence? ๐
I have a PR on the way for this. Creating an issue here for it to track. Please let me know if there is anything further you require from me and/or if I am not following a guideline exactly. This is my first time contributing. Apologies in advance for any missteps!
Output is not colored when running an .net core 2.0 project in docker non interactive mode.
This gives colored output
docker run -it yourimage
While this doesn't
docker run yourimage
MS extensions logger gives colored output
For Software Clearing purposes I need the sources for the 3.0.1. release, but when I click on the link in the Releases section, I'm only getting a 500 Internal Server Error.
I'm looking for a way to set the console color per-property but this does not appear easy to do out-of-the-box.
The context is Serilog's Level text is not really nice-looking when abbreviated. "Information" is too long, and if abbreviated to "Info", then Serilog displays weird level names like "Eror" or "debu".
To counteract this I wrote my own Level enricher, however it no longer colorizes the console based on the level.
I could not find any easy way to do this, so I instead overrode the LogEventProperty with a custom wrapper to change the console color on Render:
class ConsoleLogEventPropertyValue : LogEventPropertyValue
{
private readonly LogEventPropertyValue Value;
private readonly ConsoleColor Color;
public ConsoleLogEventPropertyValue(LogEventPropertyValue value, ConsoleColor color)
{
Value = value;
Color = color;
}
public override void Render(TextWriter output, string format = null, IFormatProvider formatProvider = null)
{
var originalColor = Console.BackgroundColor;
Console.BackgroundColor = Color;
Value.Render(output, format, formatProvider);
Console.BackgroundColor = originalColor;
}
}
class ConsoleLogEventProperty : LogEventProperty
{
public ConsoleLogEventProperty(LogEventProperty property, ConsoleColor color)
: base(property.Name, new ConsoleLogEventPropertyValue(property.Value, color))
{
}
}
There are a few issues with this though:
when Render is called, the value is rendered to the TextWriter, but it is not rendered to the console. This means setting the console color for the duration of Render doesn't actually affect when the text is written to console.
I can work around this by leaving the console color set on calling Render (this is not great because ideally you want to reset the color, but it appears Serilog already resets the color on moving to the next property anyways). The trouble with this is that the rendered text is quoted, so whereas the level was previously rendered Error, not it is rendered "Error". From what I can tell Serilog does this because of the wrapped ConsoleLogEventPropertyValue. It's doing nothing but forwarding calls to the underlying value, so from this I surmise that the sink is actually reasoning about the type and not just the value and this affects whether quotations are emitted around the value.
Anyways, it'd be great not to have to go to these lengths just to get back the default coloring and to provide a mechanism for specifying coloring for each property.
Currently, given the message template = "[{Timestamp:yyyy-MM-dd HH:mm:ss.ffff} {Level:u3}] {Message:l} {Properties}"
and providing no properties, an empty structure is printed:
[2020-01-07 15:00:24.6515 INF] Program started {Version="1.0.0.0"}
[2020-01-07 15:00:24.6920 INF] Moduel 1 Starting {}
[2020-01-07 15:00:24.6934 INF] Moduel 2 Starting {}
[2020-01-07 15:00:24.6945 INF] Moduel 3 Starting {}
[2020-01-07 15:00:24.7052 INF] Module 1 DoSomething Starting {Item="Foo"}
[2020-01-07 15:00:24.7087 INF] Module 2 DoSomething Starting {Item="Bar"}
I think that it would be nicer to not have that empty structure printed every time, like so:
[2020-01-07 15:00:24.6515 INF] Program started {Version="1.0.0.0"}
[2020-01-07 15:00:24.6920 INF] Moduel 1 Starting
[2020-01-07 15:00:24.6934 INF] Moduel 2 Starting
[2020-01-07 15:00:24.6945 INF] Moduel 3 Starting
[2020-01-07 15:00:24.7052 INF] Module 1 DoSomething Starting {Item="Foo"}
[2020-01-07 15:00:24.7087 INF] Module 2 DoSomething Starting {Item="Bar"}
Is this something that sounds reasonable?
Does this issue relate to a new feature or an existing bug?
**What version of Serilog Console Sink is affected by this issue? **
-GitHub documentation
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
Please describe the current behaviour you are experiencing?
Issue in serilog-sinks-literate Ability to direct Error and Fatal to Console.Error instead of Console.Out #6ย introduced standardErrorFromLevel parameter.
Is it supported by Console sink?
Is it possible to specify standardErrorFromLevel in appsettings.json? Example of configuration will be appreciated.
In general when a pull request with a new feature is accepted, it will be good to ensure that corresponding documentation/wiki is updated as well. Otherwise many useful features are kept hidden.
BTW, the issue template is confusing . In Console sink issue you are telling:
A few questions before you begin:...
This issue list is intended for Serilog core issues. If this issue relates to a sink or related project, please log on the related repository.
Does this issue relate to a new feature or an existing bug?
Not sure that this is a "bug" per se, it may be considered a missing "feature".
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
v3.1.1
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
Please describe the current behaviour you are experiencing?
I created a custom ANSI color theme. I noticed that the timestamp component of the output template format string was not colorized. I tried the following:
{
"Serilog": {
"WriteTo": [
{
"Name": "Console",
"Args": {
"theme": "Full Qualified Class Name of my theme",
"outputTemplate": "[\u001b[38;2;104;153;106m{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{Newline}{Exception}"
}
}
]
}
}
Please describe the expected behaviour if the ?
I expected that the timestamp component would be come an aqua green color (from Gruvbox Dark). Instead, the timestamp component remained the standard default terminal text color.
Suggested way to fix/add feature
Perhaps a new ConsoleThemeStyle
field could be added: Timestamp
.
From serilog-archive/serilog-sinks-literate#17.
We've now had experience with three different console sink designs, this one, ColoredConsole
and LiterateConsole
.
Each has strengths and weaknesses; for example, literate has nice presentation, but Console
can accept a custom formatter and produce valid JSON if required.
It's time to unify all of these. There are, as always, options. A strawman proposal:
WriteTo.LiterateConsole()
and WriteTo.ColoredConsole()
, and the corresponding NuGet packages, obsolete, directing users to WriteTo.Console()
Things I think we want without doubt:
ITextFormatter
, culturecmd.exe
, bash
(dark) and PowerShell
(default blue) terminalsLiterateConsole
and ColoredConsole
might use Windows ones by default, but we'd strongly encourage ANSI through docs/examples){Properties}
{Message:l}
(this would probably be in the default template, since color would also be on by default, making property value delimiters ("
) redundantStretch/later goals:
Type
)Other thoughts:
StructureValue
, or would the output be more predictable/meaningful for people if we instead printed complex values as (syntax-highlighted) JSON?Microsoft has logic in certain places (in VS, in Azure Web App for Containers) that detects whether your dotnet core app is running by monitoring STDOUT for certain log messages (it essentially uses log output as control messages).
This has been raised by others here:
serilog/serilog-aspnetcore#139
Their implementation seems to be very sensitive to the format that messages are written.
I appreciate the MS implementation should be improved to not be so fragile, but in addition to that, I am wandering if you could document or provide a theme / message format that maps to the out of the box console format that dotnet applications have natively. In this way, those wanting to use this sync in their dotnet core applications, can take the documented / compatible "dotnet core" format that will continue to allow MS flaky detection logic to work in the various places they have shoved it.
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
All.
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
Please describe the current behaviour you are experiencing?
As described here: serilog/serilog-aspnetcore#139
Please describe the expected behaviour if the ?
If the current behavior is a bug, please provide the steps to reproduce the issue and if possible a minimal demo of the problem
NOTE: A small code sample goes a long way in expediting bug fixes or illustrating an enhancement you are proposing.
Hi,
My System.Terminal
project is a complete replacement for System.Console
centered around VT100(-ish) terminals on Windows/Unix. One of the caveats of the project is that you can't use System.Console
at all (due to some implementation details in CoreCLR) so this sink breaks.
System.Terminal
exposes Stream
properties for the standard I/O streams which can easily be wrapped in e.g. a StreamWriter
, but it doesn't seem like there's any way to tell this sink to use them. Would it be reasonable to allow the user to pass in TextWriter
objects for stdout/stderr when configuring the sink?
From serilog/serilog-sinks-file#57 :
: I don't want my existing log parser to break (stable formatting since pre-1.0 days):j
: I primarily want machine-readable logs:l
: I primarily want human-readable logs:lj
: I want to strike a balance - machine-readable as much as possible, but accept some compromises to remove clutterThe console sink currently uses human-centric/culture-dependent formatting even when :j
is present in the Message
token's format specifier. This is inconsistent with the other text-based sinks that use the Serilog built-in MessageTemplateTextFormatter
.
We should adapt the tests in serilog/serilog#1234, added for this.
Any chance we could do a merge to master
and release a v4 of this sink? I'm currently using v3.1.1 and using reflection to set and share a syncRoot
over multiple ConsoleSinks, then I saw a recently merged PR that solves this.
A few questions before you begin:
Is this an issue related to the Serilog core project or one of the sinks or community projects. This issue list is intended for Serilog core issues. If this issue relates to a sink or related project, please log on the related repository. Please use Gitter chat and Stack Overflow for discussions and questons.
Does this issue relate to a new feature or an existing bug?
What version of Serilog Console Sink is affected by this issue? Please list the related NuGet package.
3.1.1
What is the target framework and operating system affected by this issue? Please see target frameworks & net standard matrix.
Please describe the current behaviour you are experiencing?
When we are using console sink, we realised there is a huge increase in cpu context switches even after using async. Our application is still suffering from performance issues. Setting minimum log level to INFO did not resolve the issue either. The only solution was to turn off console logging. In the long term, this is not the solution. We need console logs. I have a screenshot attached with the comparison between enabling and disabling console logging. All logging means enabling both console and file sinks.
Not sure what's wrong with console sink but i hope some expert can help us with this issue.
Log4net did not cause such performance issue previously, we hope we dont make a mistake by migrating over to Serilog.
Please describe the expected behaviour if the ?
Lower context switches when using console sink as logger, just like file sink. There is no issue when using file sink
If the current behavior is a bug, please provide the steps to reproduce the issue and if possible a minimal demo of the problem
NOTE: A small code sample goes a long way in expediting bug fixes or illustrating an enhancement you are proposing.
Create a serilog logger with both console and file sink. Call logger and write log messages multiple times in a second. (our application has a high load of processes running with many log messages at the same time). Check in process explorer - columns for the context switches and context switch delta. Compare it with and without console logging
It would be very helpful if the OutputTemplateRenderer were public. The ConsoleLoggerConfigurationExtensions.Console() allows for passing in an ITextFormatter, but because OutputTemplateRenderer is internal it's functionality cannot be leveraged. Other sinks do have their ITextFormatters as public, but this one is not.
My specific use case is that IdentityServer4 is logging email addresses in it's log messages, and we need to be able to obfuscate them before they get to the log. I initially looked into making it not do this, but it is quite non-trivial, so I opted for scrubbing it from the logger. I have it working now, but it is very much a hack due to the fact that for this specific sink the OutputTemplateRenderer is internal. The File sink was much more straightforward because it was marked public.
It would be helpful to extend the README to include example of what specifying the theme via configuration looks like in JSON and XML.
For reference :
I created this issue as result of comments in serilog/serilog-settings-configuration#77 (comment)
The ANSI themes provided with this sink look the best, but aren't supported on many Windows versions, and shouldn't be used unless the output is going to a terminal. Some users don't want theming at all.
This creates a bit of a challenge for portable apps that want to look good.
Could we create an AdaptiveConsoleTheme.Default
(plus some other portable variants like Grayscale
) that dispatches to either SystemConsoleTheme
, AnsiConsoleTheme
or ConsoleTheme.None
depending on the run-time environment?
This would choose ANSI output when supported, Windows console theming when appropriate, or no theming when output is piped or the user has indicated they do not want color output (see below).
Terminal capability detection is a bit of a minefield; http://bixense.com/clicolors/ and http://no-color.org/ propose some environment-variable-based tactics that we might also include support for.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.