Coder Social home page Coder Social logo

serilog-extensions-logging's Introduction

Serilog Build status NuGet Version NuGet Downloads Stack Overflow

Serilog is a diagnostic logging library for .NET applications. It is easy to set up, has a clean API, and runs on all recent .NET platforms. While it's useful even in the simplest applications, Serilog's support for structured logging shines when instrumenting complex, distributed, and asynchronous applications and systems.

Serilog

Like many other libraries for .NET, Serilog provides diagnostic logging to files, the console, and many other outputs.

using var log = new LoggerConfiguration()
    .WriteTo.Console()
    .WriteTo.File("log.txt")
    .CreateLogger();

log.Information("Hello, Serilog!");

Unlike other logging libraries, Serilog is built from the ground up to record structured event data.

var position = new { Latitude = 25, Longitude = 134 };
var elapsedMs = 34;

log.Information("Processed {@Position} in {Elapsed} ms", position, elapsedMs);

Serilog uses message templates, a simple DSL that extends .NET format strings with named as well as positional parameters. Instead of formatting events immediately into text, Serilog captures the values associated with each named parameter.

The example above records two properties, Position and Elapsed, in the log event. The @ operator in front of Position tells Serilog to serialize the object passed in, rather than convert it using ToString(). Serilog's deep and rich support for structured event data opens up a huge range of diagnostic possibilities not available when using traditional loggers.

Rendered into JSON format for example, these properties appear alongside the timestamp, level, and message like:

{"Position": {"Latitude": 25, "Longitude": 134}, "Elapsed": 34}

Back-ends that are capable of recording structured event data make log searches and analysis possible without log parsing or regular expressions.

Supporting structured data doesn't mean giving up text: when Serilog writes events to files or the console, the template and properties are rendered into friendly human-readable text just like a traditional logging library would produce:

09:14:22 [INF] Processed {"Latitude": 25, "Longitude": 134} in 34 ms.

Upgrading from an earlier Serilog version? Find release notes here.

Features

  • Community-backed and actively developed
  • Format-based logging API with familiar levels like Debug, Information, Warning, Error, and so-on
  • Discoverable C# configuration syntax and optional XML or JSON configuration support
  • Efficient when enabled, extremely low overhead when a logging level is switched off
  • Best-in-class .NET Core support, including rich integration with ASP.NET Core
  • Support for a comprehensive range of sinks, including files, the console, on-premises and cloud-based log servers, databases, and message queues
  • Sophisticated enrichment of log events with contextual information, including scoped (LogContext) properties, thread and process identifiers, and domain-specific correlation ids such as HttpRequestId
  • Zero-shared-state Logger objects, with an optional global static Log class
  • Format-agnostic logging pipeline that can emit events in plain text, JSON, in-memory LogEvent objects (including Rx pipelines) and other formats

Getting started

Serilog is installed from NuGet. To view log events, one or more sinks need to be installed as well, here we'll use the pretty-printing console sink, and a rolling file set:

dotnet add package Serilog
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Sinks.File

The simplest way to set up Serilog is using the static Log class. A LoggerConfiguration is used to create and assign the default logger, normally in Program.cs:

using Serilog;

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .WriteTo.File("log.txt",
        rollingInterval: RollingInterval.Day,
        rollOnFileSizeLimit: true)
    .CreateLogger();

try
{
    // Your program here...
    const string name = "Serilog";
    Log.Information("Hello, {Name}!", name);
    throw new InvalidOperationException("Oops...");
}
catch (Exception ex)
{
    Log.Error(ex, "Unhandled exception");
}
finally
{
    await Log.CloseAndFlushAsync(); // ensure all logs written before app exits
}

Find more, including a runnable example application, under the Getting Started topic in the documentation.

Getting help

To learn more about Serilog, check out the documentation - you'll find information there on the most common scenarios. If Serilog isn't working the way you expect, you may find the troubleshooting guide useful.

Serilog has an active and helpful community who are happy to help point you in the right direction or work through any issues you might encounter. You can get in touch via:

We welcome reproducible bug reports and detailed feature requests through our GitHub issue tracker; note the other resource are much better for quick questions or seeking usage help.

Contributing

Would you like to help make Serilog even better? We keep a list of issues that are approachable for newcomers under the up-for-grabs label (accessible only when logged into GitHub). Before starting work on a pull request, we suggest commenting on, or raising, an issue on the issue tracker so that we can help and coordinate efforts. For more details check out our contributing guide.

When contributing please keep in mind our Code of Conduct.

Detailed build status

Branch AppVeyor
dev Build status
main Build status

Serilog is copyright © Serilog Contributors - Provided under the Apache License, Version 2.0. Needle and thread logo a derivative of work by Kenneth Appiah.

serilog-extensions-logging's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

serilog-extensions-logging's Issues

Publish update?

This is really deprecated? If not, I'd like an updated nuget push of this. I seem to having version conflicts when trying to use beta-700 of colored console and periodic batching sink.

Suspected incompatibility between Serilog.Extensions.Logging 1.3.0 and Microsoft.AspNetCore.AzureAppServicesIntegration 1.0.0

I started upgrading my apps to .NET core 1.1.0 and decided to use the Microsoft.AspNetCore.AzureAppServicesIntegration package. It has a dependency on Microsoft.Extensions.Logging.AzureAppServices which has a dependency on Serilog.Extensions.Logging>=1.0.0.

My apps have a direct dependency on Serilog.Extensions.Logging 1.3.0 and I can't get them to work in Azure. I was able to capture this stacktrace below.

I have a github repo here: https://github.com/npnelson/AzureAppServiceSerilogBug

I'm guessing Serilog.Extensions.Logging removed a method needed by Microsoft.Extensions.Logging.AzureAppServices somewhere along the way.

Unhandled Exception: System.MissingMethodException: Method not found: 'Microsoft.Extensions.Logging.ILoggerFactory Serilog.SerilogLoggerFactoryExtensions.AddSerilog(Microsoft.Extensions.Logging.ILoggerFactory, Serilog.ILogger)'. at Microsoft.Extensions.Logging.AzureAppServices.Internal.AzureAppServicesDiagnosticsLoggerProvider..ctor(WebAppContext context, AzureAppServicesDiagnosticsSettings settings) at Microsoft.Extensions.Logging.AzureAppServicesLoggerFactoryExtensions.AddAzureWebAppDiagnostics(ILoggerFactory factory, AzureAppServicesDiagnosticsSettings settings) at Microsoft.Extensions.Logging.AzureAppServicesLoggerFactoryExtensions.AddAzureWebAppDiagnostics(ILoggerFactory factory) at Microsoft.AspNetCore.Hosting.AppServicesWebHostBuilderExtensions.<>c.<UseAzureAppServices>b__0_0(ILoggerFactory loggerFactory) at Microsoft.AspNetCore.Hosting.WebHostBuilder.BuildCommonServices() at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build() at <Redacted>.Program.Main(String[] args) in C:\agent\_work\5\s\src\<Redacted>\Program.cs:line 15

Unable to reference Serilog in Full .NET Framework project

I'm working on a full .NET Framework Windows Service and trying to reference the SeriLog extension. When I do I get the following error:

Failed to add reference to 'System.Runtime'. Please make sure that it is in the Global Assembly Cache.

I believe it may be because of the following in the project.json file of this repo.

"net4.5": {
  "frameworkAssemblies": {
    "System.Runtime": ""
  }
}

If you add System.Runtime as a straight dependency instead of as a frameworkAssemblies entry this should then work as expected

Target error installing rc1 on .NET 4.5.2

I am using the framework in a .NET 4.5.2 project. When I try to install rc1 (10071) I get the following error:
"Could not install package 'Serilog.Framework.Logging 1.0.0-rc1-final-10071'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5.2', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author."
I tried changing the target to 4.5.1 and 4.5 without success.
The previous beta8 (10065) installs correctly.

Cannot add to a Web Api project

I've tried many different version of the .net framework, 4.5.1, 4.5.2, 4.6, 4.6.1 and fails to install. With the same error.

PM> Install-Package Serilog.Framework.Logging -Pre
Attempting to gather dependencies information for package 'Serilog.Framework.Logging.1.0.0-rc1-final-10083' with respect to project 'WebApplication2', targeting '.NETFramework,Version=v4.5.2'
Attempting to resolve dependencies for package 'Serilog.Framework.Logging.1.0.0-rc1-final-10083' with DependencyBehavior 'Lowest'
Resolving actions to install package 'Serilog.Framework.Logging.1.0.0-rc1-final-10083'
Resolved actions to install package 'Serilog.Framework.Logging.1.0.0-rc1-final-10083'
Adding package 'Serilog.Framework.Logging.1.0.0-rc1-final-10083' to folder 'C:\Users\anthony.miller\documents\visual studio 2015\Projects\WebApplication2\packages'
Added package 'Serilog.Framework.Logging.1.0.0-rc1-final-10083' to folder 'C:\Users\anthony.miller\documents\visual studio 2015\Projects\WebApplication2\packages'
Install failed. Rolling back...
Package 'Serilog.Framework.Logging.1.0.0-rc1-final-10083 : Microsoft.Extensions.Logging [1.0.0-rc1-final, ), Serilog [2.0.0-beta-423, )' does not exist in project 'WebApplication2'
Removing package 'Serilog.Framework.Logging.1.0.0-rc1-final-10083 : Microsoft.Extensions.Logging [1.0.0-rc1-final, ), Serilog [2.0.0-beta-423, )' from folder 'C:\Users\anthony.miller\documents\visual studio 2015\Projects\WebApplication2\packages'
Removed package 'Serilog.Framework.Logging.1.0.0-rc1-final-10083 : Microsoft.Extensions.Logging [1.0.0-rc1-final, ), Serilog [2.0.0-beta-423, )' from folder 'C:\Users\anthony.miller\documents\visual studio 2015\Projects\WebApplication2\packages'
Install-Package : Failed to add reference to 'System.Runtime'. Please make sure that it is in the Global Assembly Cache.
At line:1 char:1

  • Install-Package Serilog.Framework.Logging -Pre
  • - CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
    - FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand
    
    

Sometimes it states that System.Collections.Concurrent is not in the GAC.

NuGet only targets DNX

I'm using Logging along side .NET 4.5 projects as well as DNX ones. The Microsoft.Framework packages also allow for non-DNX usage (if it makes sense). So Logging and Configuration do.

Would it be too much trouble to add this?

I've tried to make my own project.jsons target DNX and .NET. However, the nupkgs they produce don't work for .NET for some reason because of some dependency issues. I have no idea why as mine look about the same as the nupkg from the ASP.NET team. Maybe you'll have better luck :)

Warning from PropertyBinder in Serilog: "Required properties not provided for: ... "

When I log messages, the log messages are formatted correctly, however there are messages in SelfLog that properties are not provided (although they've obviously have been passed since final messages is correct)

Example - for each entry in a rolling file sink:
2015-11-02 13:44:03.016 -05:00 [Verbose] AD lookup completed in 1835ms

There is a corresponding message in SelfLog:
2015-11-02T13:44:03 Required properties not provided for: AD lookup completed in {ADLookupMiliseconds}ms

Can you add a test for this case - write to log and check that SelfLog is empty (confirming that there are no issues raised by Serilog).

P.S. I'm not being able to run the unit tests on VS2015 Enterprise. Which version of VS was used for the unit test project?

`SerilogLoggerProvider` should dispose the associated logger, if set

Via: http://stackoverflow.com/questions/38286140/how-to-dispose-of-serilog-2-0-correctly-in-asp-net-core-application

If the provider is using the static Log pipeline, the application should be responsible for disposal as there's no indication of any ownership transfer.

If a disposable Logger instance is passed in, disposing it is reasonable. To make this explicit, we could:

  1. overload AddSerilog() with a method specifically accepting Logger
  2. or, make the overload generic where TLogger: ILogger, IDisposable
  3. or, add a dispose: default Boolean parameter to AddSerilog()
  4. or, add a new method like AddSerilogAndDispose() for the purpose.

The decision here depends on whether we want to move towards disposing by default (1 or 2) or not (3 or 4).

If we want to dispose by default, (1) is probably the friendliest option, while (3) seems like the tidiest opt-in mechanism.

How to add CategoryName to output

By default Serilog does not output the CategoryName e.g.:

var logger = loggerFactory.CreateLogger("test");

I tried a couple of templates - e.g.

.WriteTo.Trace(outputTemplate: "{Timestamp} [{Level}] ({CategoryName:l}) {Message}{NewLine}{Exception}")

but it does not work - any pointers?

thanks

Error : "Could not load..."

  1. I have error:

    "Could not load type 'Microsoft.Framework.Logging.SerilogLoggerFactoryExtensions' from assembly 'Serilog.Framework.Logging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.":"Microsoft.Framework.Logging.SerilogLoggerFactoryExtensions"

  2. I used:

    "Microsoft.Framework.Logging": "1.0.0-",
    "Serilog.Framework.Logging": "1.0.0-
    ",

  3. which probably convert to:

    "Microsoft.Framework.Logging": "1.0.0-rc1-15644"
    "Serilog.Framework.Logging": "1.0.0-rc1-final-10071"

  4. When I return to:

    "Microsoft.Framework.Logging": "1.0.0-beta8",
    "Serilog.Framework.Logging": "1.0.0-beta8-10056",

all work correctly.

Make SerilogLogger type public

Since the only public type in this package is the extension methods of the logger factory, if you want to create a logger instance, you always have to go through the factory.

For the WebApps logger, we just need an instance of the serilog logger, but that forces us to create an factory before we can create the logger. It would be useful to have that type public so we can instantiate it directly.

Log file is always in use

Consider the following scenario:
I want to see a fresh log while testing a production site - meaning I can't shutdown the site for this.
The easiest solution would be to delete the current log file so that all newly logged lines will appear in a new file so I'll have easier time seeing the request I make in order to debug an issue.
Currently I can't delete a log file because it's being used.
Feature suggestion: allow deleting a log file while am asp.core site is running and the newly added log lines will create a new file.

Treat Scopes as FromContext()

It looks like .FromContext() is almost same as Scopes. If those can be tied directly then no need to implement dependency to Serilog on classes which is a perfect reason to try/switch serilog since it will not add additional overhead to the classes as external dependency.

>= DNX Beta5 compatible nuget package publish

This is an easy one :-)

Any chance of publishing the latest as a Nuget package; the current '1.0.0-beta-2' version is dependant on MS beta4 with the now defunct '.Interfaces' package.

It's not currently possible to work on DNX projects >= Beta5, straight out of Nuget at the moment.

Thanks.

Support for beta7

The code that used to work before stopped working all of a sudden. Am I missing something?

var logger = new LoggerConfiguration()
    .MinimumLevel.Warning()
    .CreateLogger();

loggerFactory.AddSerilog(logger);

Throws:

System.TypeLoadException
Method 'Dispose' in type 'Serilog.Framework.Logging.SerilogLoggerProvider' from assembly 'Serilog.Framework.Logging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
   at Microsoft.Framework.Logging.SerilogLoggerFactoryExtensions.AddSerilog(ILoggerFactory factory, ILogger logger)

Doesn't show in Visual Studio Output Pane

I followed the instructions and I still cannot get any log messages to display in Visual Studio's Output Pane.
startup
appconfig

I added logging messages to one of my controllers. The default logger shows up just as expected, but Serilog doesn't show any output.
incontroller

This is all that is displayed in output when I run the application and hit the controller:
output

WriteOut the logger-Name ILogger<T>

How I get the name of the Logger class in SeriLog dump out? The EventId I get with a property.
But If I created a Logger

factory.CreateLogger<MySampleService>()

I want to see something like "MySampleService" in my output?

Microsoft default implementation writes

info: MySampleService[4711]
      Framework: .NET Core 4.6.24410.01
fail: MySampleService[4711]
      Error System.ArgumentException: Wrong Argument
System.ArgumentException: Wrong Argument

With the Serilog Provider I get

2016-11-24 11:12:02 { Id: 4711 }   [Information] OS: "Microsoft Windows 6.1.7601 S"
2016-11-24 11:12:02 { Id: 4711 }   [Information] Framework: ".NET Core 4.6.24410.01"
2016-11-24 11:12:02 { Id: 4711 }   [Error] Error "System.ArgumentException: Wrong Argument"
System.ArgumentException: Wrong Argument
.WriteTo.ColoredConsole(
                        LogEventLevel.Verbose, 
                        "{Timestamp:yyyy-MM-dd HH:mm:ss} {EventId} [{Level}] {Message}{NewLine}{Exception}")

Serilog v1.5 required? v2 not compatibile?

I'm using these dependencies:

"dependencies": {
    "Microsoft.Extensions.Logging": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
    "Serilog": "2.0.0-beta-423",
    "Serilog.Framework.Logging": "1.0.0-rc1-final-10075"
  }

And this line: loggerFactory.AddSerilog(); throws this error:

Severity    Code    Description Project File    Line    Suppression State
Error   CS0012  The type 'ILogger' is defined in an assembly that is not referenced. You must add a reference to assembly 'Serilog, Version=1.5.0.0, Culture=neutral, PublicKeyToken=24c2f752a8e58a10'. <project>.DNX Core 5.0  <project>\Startup.cs    81  Active

Retrieve `ILogger` from `IServiceProvider`

I read in aspnet/Logging#182 this project will use the ILogger implementation from Log.Logger if none is specified.

I understand and appreciate the need for the static/global Log; however, its seems out of place to me in cases where dependency injection is first class like in the ASP.NET 5 framework. There, it would seem more appropriate to get one from the IServiceProvider that is used for dependency resolution.

While, the current implementation works and users can choose to resolve via the DI mechanism themselves; however, I am wondering whether it would be worthwhile to have an API where serilog-framework-logging would try to resolve/retrieve the ILogger before falling back to the static Log. This could be an extension method on IApplicationBuilder that uses IApplicationBuilder.ApplicationServices meaning usage would be along the lines of app.UseSerilog().

Support for destructuring

Hi,

What are your thoughts on supporting object destructuring underneath this MS abstraction?

From what I can see at the moment in this implementation, it isn't supported either for Scope state or for the log message; it seems the MS abstraction doesn't model the concept so I can see there's not an immediately obvious solution. To clarify what I mean:

Microsoft.Framework.Logging.ILogger myLogger = loggerFactory.CreateLogger("test");

var myEntity = new MyEntity() { Id = "1234", Tags = new [] { "one", "two" } };

using (myLogger.BeginScope("{@entity1}", myEntity)) {
   myLogger.LogInformation("Here is my entity : {@entity2}", myEntity);
}

Writing to a Mongo sync for example, I get the following properties:

{
    "_id" : ObjectId("5592bad238158a2a6c2ba017"),
    "Timestamp" : ISODate("2015-06-30T15:50:41.495Z"),
    "Level" : "Information",
    "MessageTemplate" : "Here is my entity : {@entity2}",
    "RenderedMessage" : "Here is my entity : {@entity2}",
    "Properties" : {
        "@entity2" : "SerilogWebAppSample.MyEntity",
        "SourceContext" : "test",
        "@entity1" : "SerilogWebAppSample.MyEntity",
        "{OriginalFormat}" : "{@entity1}",
        "RequestId" : "80000158-0000-db00-b63f-84710c7967bb"
    },
    "UtcTimestamp" : "2015-06-30 15:50:41Z"
}

Where as of course it would be nice to be able to get:

{
    "_id" : ObjectId("5592bad238158a2a6c2ba017"),
    "Timestamp" : ISODate("2015-06-30T15:50:41.495Z"),
    "Level" : "Information",
    "MessageTemplate" : "Here is my entity : {@entity2}",
    "RenderedMessage" : "Here is my entity : { Id: \"1234\", Tags: [\"one\", \"two\"] }",
    "Properties" : {
         "entity1" : {
            "_typeTag" : "MyEntity",
            "Id" : "1234",
            "Tags" : [ 
                "one", 
                "two"
            ]
        },
        "SourceContext" : "test",
        "entity2" : {
            "_typeTag" : "MyEntity",
            "Id" : "1234",
            "Tags" : [ 
                "one", 
                "two"
            ]
        },
        "{OriginalFormat}" : "{@entity1}",
        "RequestId" : "80000026-0001-c300-b63f-84710c7967bb"
    },
    "UtcTimestamp" : "2015-06-30 15:50:41Z"
}

Any thoughts?

Logging Issue in ASP.NET Core Web Api

In asp.net core 1.1.1, using the serilog-extensions-logging, doesn't log and create log files under rollingfile sink but creates a file but doesn't log under file sink. Somehow the LitearteConsole is working. Strange though, any solution appreciated...my initialization code under Startup.cs is as follows:
`

        Configuration = builder.Build();

        string logLocation = Configuration.GetValue<String>("LogLocation:Path") + "log-{Date}.txt";
        string logFileLocation = Configuration.GetValue<String>("LogLocation:Path") + "log.txt";
        //string logLocation = Path.Combine(env.ContentRootPath, "log-{Date}.txt");

        var logger = new LoggerConfiguration()
                        .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                        .MinimumLevel.Override("System", LogEventLevel.Warning)
                        .WriteTo.LiterateConsole()
                        .WriteTo.File(path: logFileLocation, fileSizeLimitBytes: 10737418) //100 MB
                        //.WriteTo.RollingFile(pathFormat: logLocation, retainedFileCountLimit:7, fileSizeLimitBytes:10737418) //100 MB
                        .CreateLogger();

Code under Configure:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
                    IApplicationLifetime appLifetime)
    {
        //loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
        loggerFactory.AddSerilog();
        appLifetime.ApplicationStopped.Register(Log.CloseAndFlush);

appsettings value for logLocation: "LogLocation": {"Path": "C:\Bootstrap-api\Logs\"}
Serilog.Extensions.Logging ver 1.4.0

How to disable default logging?

Sorry if this is not the correct place to address this (if not, let me know where I should go). Also, I'm new to .NET Core, Web API, etc.

I setup the logger and its working, however there seems to be some default logging events coming from Core/WebAPI/etc. that I would like to disable. Essentially, the only logging I want to see is when I explicitly log (such as _logger.LogError()).

public Startup(IHostingEnvironment env)
{
    Log.Logger = new LoggerConfiguration()
        .Enrich.FromLogContext()
        .WriteTo.LiterateConsole()
        .CreateLogger();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddSerilog();
    app.UseMvc();
}

Without any other logging code, console is showing (this is what I don't want)...

[09:59:47 INF] Request starting HTTP/1.1 GET http://localhost:5000/api/values
[09:59:47 INF] Executing action method TodoAPI.Controllers.ValuesController.Get (TodoAPI) with arguments (null) - ModelState is Valid
[09:59:47 INF] Executing ObjectResult, writing value Microsoft.AspNetCore.Mvc.ControllerContext.
[09:59:48 INF] Executed action TodoAPI.Controllers.ValuesController.Get (TodoAPI) in 280.4201ms
[09:59:48 INF] Request finished in 599.358ms 200 application/json; charset=utf-8

Thanks for any help!

Adding settings to config file in .NET Core

I have SeriLog working in my .NET Core web app. I've configured it in my Startup class like this:

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .WriteTo.RollingFile("C:/LogFiles/log-{Date}.txt")
    .CreateLogger();

I'd like to pull out configuration properties like the min log level and rolling file path to a file. In .NET Core, it would seem either the appsettings.json file or web.config file would be appropriate. In my project, I have these environment-specific versions for these files.

How can I move configuration properties to a config file in .NET Core?

Where does Serilog output its logs when following the getting started guide?

I'm testing out serilog in an aspnet5 rc1 final project and having a bit of trouble writing out to the console. However when i fire the web method below nothing appears in the visual studio output window. I must be missing something, anybody know what I am doing wrong?

startup.cs

public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
    Log.Logger = new LoggerConfiguration().WriteTo.TextWriter(Console.Out).CreateLogger();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddSerilog();
}

web controller

[HttpPost]
public async Task get()
{
    Log.Verbose("hello", new {});
}

dependencies section of project.json looks like this

    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging": "1.0.0-rc1-final",
    "Microsoft.AspNet.Authentication.JwtBearer": "1.0.0-rc1-final",
    "Serilog.Framework.Logging": "1.0.0-rc1-final-10071",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final"

Attach hierarchical scope to log events

Currently, BeginScope() will cause any properties on the state object to be attached to resulting events:

https://github.com/serilog/serilog-extensions-logging/blob/dev/src/Serilog.Extensions.Logging/Extensions/Logging/SerilogLoggerScope.cs#L53

and:

https://github.com/serilog/serilog-extensions-logging/blob/dev/src/Serilog.Extensions.Logging/Extensions/Logging/SerilogLoggerProvider.cs#L61

However, it's also possible to use string "names" with scopes, and in that case some form of scope path should be attached to the event. For example:

using (log.BeginScope("A"))
{
    using (log.BeginScope("B")
    {
        log.LogInformation("Hello");
    }
}

produces a scope like "A -> B" in the default console logger output.

Serilog might attach these as a Sequence property, e.g. (in JSON rendering) "Scope": ["A", "B"].

Log method that allows lazily evalution of (Func<string>)

Howdy,

Is it possible to achieve something like this OOTB: _logger.LogInformation(() => $"Complex computed result just before doing something else was: {DoTheMath}"); where DoTheMath is potentially an expensive call, which we don't want to make when logging only the messages with high severity (criticals/fatals)?

If there is, can you please point me to a self-contained sample? 8-)

If not, any ideas how should I go about creating another wrapper over serilog-extensions-logging, that can fit into ASP.NET logging abstractions pipeline (without altering their default DI mechanics)?

Thanks!

Trace vs Verbose

Serilog has a loglevel Verbose. Microsofts implementation does not. However it dóes have the loglevel Trace. Shouldn't these map to eachother?

Right now when restrictedToMinimumLevel is set to Verbose (or Debug), messages logged as Trace are not written to the log by Serilog.

Can't figure out BeginScope?

Hi,

I'm having issues with the extension in a .Net Core Console Application, where I can't get the BeginScope function to do anything when using the Serilog extension.

I'm creating the logger like so:

Log.Logger = new LoggerConfiguration().Enrich.FromLogContext().WriteTo.LiterateConsole().CreateLogger();

And using the logger like so (as per #50 ):

var logger = new LoggerFactory().AddSerilog().CreateLogger(type)
var counter = 1;
var threadid = 2;
using( logger.BeginScope( "Test {counter} # {threadid}", counter, threadid ) )
{
    foreach( var registeredMethod in registeredMethods )
    {
        logger.LogInformation( "test | {0}", "abc" );
    }
}

However, I can't seem to get the scope to print anything at all to the console (nor using the flatfile extension):
image

What am I doing wrong here?

HostingScope gets decomposed and not rendered in {Scope} format

When using Console logger with includeScopes=true all scopes gets rendered with a log message, I think users would expect similar behavior from {Scope} format, instead hostings scope state gets decomposed into properties and not logged as part from {Scope}.

Expected output:

2017-02-15 15:28:34 [Information] ["RequestId:0HL2LV9E249UM RequestPath:/", "Main", "Main2"] Waiting for user input

Actual output:

2017-02-15 15:28:34 [Information] ["Main", "Main2"] Waiting for user input

Repro code:

using System;
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;

namespace LogScopeOnAzure
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }

    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            var loggers = new Serilog.LoggerConfiguration().WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Scope} {Message}{NewLine}{Exception}");
            loggerFactory.AddSerilog(loggers.CreateLogger());
            loggerFactory.AddConsole(true);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                var logger = context.RequestServices.GetService<ILogger<Startup>>();
                logger.LogCritical(1, "Unexpected critical error starting application");
                logger.LogError(1, "Unexpected error");
                logger.LogWarning(1, "Unexpected warning");


                using (logger.BeginScope("Main"))
                using (logger.BeginScope("Main2"))
                {

                    logger.LogInformation("Waiting for user input");
                    
                    logger.LogInformation("User typed '{input}' on the command line", "Inpuit");
                    logger.LogWarning("The time is now {Time}, it's getting late!", DateTimeOffset.Now);
                    await context.Response.WriteAsync("Hello World!");
                }
            });
        }
    }
}

Destructuring operator doesn't work

I'm playing with Serilog.Framework.Logging and I noticed the following issue when using the Serilog destructuring paramter ("@"): I think it's best if I illustrate it with some code. Here my test code:

class Foo
{
    public string SValue { get; set; }
    public int IValue { get; set; }
}

[Test]
public void StructuredLogging()
{
    Log.Logger = new LoggerConfiguration().MinimumLevel.Information()
        .WriteTo.Seq("http://localhost:5341")
        .CreateLogger();

    var loggerFactory = new LoggerFactory();
    loggerFactory.AddSerilog(Log.Logger);

    var logger = loggerFactory.CreateLogger(typeof(SerilogTests).FullName);

    var foo = new Foo { SValue = "some value", IValue = 42 };
    Log.Information("Serilog message {@value}", foo);
    logger.LogInformation("M.F.L message: {value}", foo);
    logger.LogInformation("M.F.L message: {@value}", foo);
}

I.e. I'm writing a log message to Microsoft.Framework.Logging after configuring it to use Serilog as well as writing a log message directly through the Serilog API. Here the result:

screenshot

As you can see the message I wrote using the Serilog API directly (last one in the screenshot) properly destructures the Foo object. However, the message written through M.F.Logging doesn't.

I did some debugging and I noticed that writing to Serilog directly ends up calling

Logger.Write(LogEventLevel.Information, exception, messageTemplate, propertyValues);

where propertyValues is an array of 1 element containing the Foo object.

Serilog.Framework.Logging also ends up calling this method, however the call looks as follows (see SerilogLogger.Log():

logger.Write(level, exception, messageTemplate);

Here we don't provide the Foo object as parameter. Instead it was added using ForContext() a couple of lines earlier.

Now, it seems that approach works fine when using "regular" placeholders in the message template string (e.g. "{value}"), but it doesn't seem to properly work with the destructuring parameter (e.g. "{@value}").

Is there anything I can do to get this working? Or is this a known issue/limitation?

Thanks for your help!

Allow configuration using LogLevel similar to ms loggers

Default aspnet logger allows me to throw at it variables from config file like:

  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }

Looks like it is impossible in serilog. My use case is that I am using serilog only for rolling file, while default console and debug loggers are running through built in loggers.
What log level property does (I think) - it limits sink level based on "SourceContext" property (I'm, not sure though).

Should there be additional overload on AddSerilog using IConfiguration and doing this?

.NET Core RC2 net451 monikor isn't supported

My project runs on core but the net451 framework.

Package Serilog.Extensions.Logging 1.0.0-rc2-10096 is not compatible with net451 (.NETFramework,Version=v4.5.1). Package Serilog.Extensions.Logging 1.0.0-rc2-10096 supports: netstandard1.3 (.NETStandard,Version=v1.3)

It might be me doing something dumb, I have to admit I'm not 100% sure I'm doing the transformation correctly with all the name changes. All other packages (Autofac and NServiceBus for example) work fine).

Formatter is not always called, by Log method

I'm passing a modified "formatter" function into the Log method. However, its not getting called. The reason appears to be that "state is IEnumerable<KeyValuePair<string, object>>== true", and in that code path, there seem to be cases where formatter is not called. Is that by design, or a bug?

Cannot load assembly "Microsoft.Extensions.Logging.Abstractions" on full framework

.net 4.6.1 WCF service, with

    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>

and

    <PackageReference Include="Microsoft.Extensions.Logging">
          <Version>1.1.1</Version>
    </PackageReference>
    <PackageReference Include="Serilog.Extensions.Logging">
          <Version>1.4.0</Version>
    </PackageReference>

WcfService.dll.config in output contains

    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="Microsoft.Extensions.Logging.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-1.1.1.0" newVersion="1.1.1.0" />
          </dependentAssembly>
        </assemblyBinding>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="System.Security.Cryptography.X509Certificates" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-4.1.1.0" newVersion="4.1.1.0" />
          </dependentAssembly>
        </assemblyBinding>
      </runtime>

Microsoft.Extensions.Logging.Abstractions.dll in output has version 1.1.1.

In runtime I got Could not load file or assembly ' Microsoft.Extensions.DependencyInjection.Abstractions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. (note - version is 1.0.0)

After removing Microsoft.Extensions.Logging package, only 1.0.0-trm-21431 version of Microsoft.Extensions.Logging.Abstractions.dll is in output. After removing Serilog.Extensions.Logging package, no Microsoft.Extensions.Logging.Abstractions.dll.

For .net Core console/web app same packages combintaion works.

How to disable Entity Framework Core SQL Queries logging?

I've Asp.Net Core project with Serilog and Serilog extensions logging. And I want to disable all SQL queries, that EF Core logs in information level. I've found this article, but it says to filter logs by category - and I haven't found an ability to do so in Serilog.

//Config in Startup.cs:
//Startup constructor:
            Log.Logger = new LoggerConfiguration()
               .MinimumLevel.Information()
               .WriteTo.RollingFile(pathFormat: Path.Combine(Configuration.GetSection("SerilogPath").Value, "log-{Date}.txt"), fileSizeLimitBytes: 100000, retainedFileCountLimit: 1)
               .CreateLogger();
//Configure method:
            loggerFactory.AddSerilog();
            appLifetime.ApplicationStopped.Register(Log.CloseAndFlush);

BeginScope does not log message

using (logger.BeginScope("@Foo1 @Foo2 ignored", foo1, foo2))
{
    ...
}

This highlights a small discrepancy between the MFL BeginScope signature and the current Serilog implementation, in that BeginScope takes messageFormat and args, implying that you can log a message. Whereas the Serilog implementation will only honour any properties defined inside the message format, and ignore everything else.

Is it suitable to log the message provided in BeginScope? Of course there can potentially be multiple nested scopes, so 'scope messages' will be different to the rendered message.

Microsoft's sample implementations seem to not do anything on a BeginScope - so maybe it's fine to only partially honour the interface. It's just unfortunate that the interface is misleading, and makes it a little more complicated to explain to end users.

Debug vs Verbose

I understand MF.Logging and Serilog have different priority levels but it's really bothersome to see logger.LogDebug show up as Verbose in serilog.

Is that the final word on how this should work?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.