Giter Site home page Giter Site logo

serilog-sinks-browserconsole'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-sinks-browserconsole's People

Contributors

maximst92 avatar nblumhardt avatar zbecknell avatar zetroot avatar

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

Watchers

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

serilog-sinks-browserconsole's Issues

Use JSRuntime.Current

In BrowserConsoleSink.cs#L27 you are instantiating a new IJSRuntime instance.

Is there a reason why you are not using JSRuntime.Current like described in the docs?

I'm asking because this seems to interfere with other interop calls.

Version 2.0.0 release plan

It seems that it's been half a year since the release of 2.0.0-dev-00057 . Is there a plan to finish this release? Are there any bugs or other open issues obstructing the final release? Can we help?

Tnx to all contributors.

Dotnet 6 compatibility

Dotnet 6 has been released for a while now and it would be great if this sink could be released targeting .net 6 too.
Multi-targeting (including netstandard2.0) would be even better probably.

Example taken from: https://github.com/serilog/serilog-sinks-console/blob/dev/src/Serilog.Sinks.Console/Serilog.Sinks.Console.csproj

    <TargetFrameworks>net45;netstandard1.3;netstandard2.0;net5.0</TargetFrameworks>

Would solve this issue:

/Users/klaus/projects/test/UI/src/Web/Web.csproj : error NU1100: Unable to resolve 'Serilog.Sinks.BrowserConsole (>= 1.0.0)' for 'net6.0'.

browserconsole not working with .net5 blazor rc1

Using a Blazor web assembly .NET 5 rc1 app.

Serilog configuration runs without error, but I am not seeing any web browser console output in Chrome. Is it possible something broke with newer releases of blazor?

Adding serilog.sinks.browserconsole causes JsInterop to fail in Blazor WebAssembly.

Adding serilog.sinks.browserconsole causes JsInterop to fail in Blazor WebAssembly.

I have created a simple example repository to show the issue which can be found here:
example serilog.sinks.browserconsole problem

This is a default Visual Studio Blazor WebAssembly template (.net core hosted) with a service and some JsInterop that I've added to get and set values in the browser's session storage (used inside MainLayout).

On first run you will see that it fails to return a value, however if you comment out: .WriteTo.BrowserConsole() inside Program.cs, you will see that it works.

I did notice another issue posted here, however I think it was Blazor Server related and not Blazor WebAssembly.

Although I'm unsure, I believe the issue is related to having a service that also injects JSRuntime (SessionStorageService.cs in the example), as I believe if you just keep this JsInterop code inside the component, it will work, but this is not ideal.

JSRuntime.InvokeAsync issue

Firstly, excellent work that we have this sink.

Kindof related to #20
Create a New .Net8 WASM app (hosted)
Add a simple javascript file to client wwwroot folder

In program.cs
create WebAssemblyHostBuilder
Add Serilog BrowserConsole
Log something
Now build the WebAssemblyHostBuilder
Get the JSRuntime from DI container
try to import a module using JSRuntime - module is returned as null

The expected behaviour is the module is returned as an IJSObjectReference

If I don't use the Logger before getting the module - it works
A workaround is to put the module import in a loop, this works and it succeeds on the second try.

Another workaround as suggested in issue #20 is to pass the JSRuntime to the BrowserConsole sink. However, I do many things prior to building the DI container(initialising dynamically loaded modules etc), so I need to be able to log before building the WebAssemblyHostBuilder. This workaround is not an option for me and this scenario needs to be considered for issue #20.

The behaviour is the same using dotnet run and dotnet watch. So I don't think this is a tooling issue.

So while I have a workaround, there is clearly something here that is changing the default behaviour of JSRuntime.

Example repo is here

`outputTemplate:` support

Although this sink can't use the built-in output template formatting directly, it should still be possible to accept and control output using a regular output template, e.g.:

WriteTo.BrowserConsole(outptTemplate: "{Message} {Properties}{NewLine}{Exception}")

The regular Console sink does something similar to support theming.

Breaks a WASM .NET 7 app

If we initialize the app with this sink, the app throws a null reference exception on the initialization of the app, causing it to fail to start.

System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.AspNetCore.Components.WebAssembly.HotReload.WebAssemblyHotReload.InitializeAsync() at Microsoft.AspNetCore.Components.WebAssembly.Hosting.WebAssemblyHost.RunAsyncCore(CancellationToken cancellationToken, WebAssemblyCultureProvider cultureProvider) at Program.<Main>$(String[] args) in C:\xxxxxxxxxxx\Program.cs:line 147

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.