Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Using 2 different configured NLog Loggers with Microsoft.Extensions.ILogger and Dependency Injection

$
0
0

I want to use 2 different configured NLog Loggers (one should log to a Database, the other to console) in a Blazor Server App and use them both in my services as individual objects using Microsoft.Extensions.ILogger with Dependency Injection.

This is a snippet of my nlog.config

<targets><target name="databaseTarget" xsi:type="Database" dbProvider="Oracle.ManagedDataAccess.Client.OracleConnection, Oracle.ManagedDataAccess" connectionString="${configsetting:name=DatabaseConfiguration.ConnectionString}" commandType="Text"><commandText>            INSERT INTO SCHEMA.LOG ("Timestamp", "Level", "Logger", "Message", "Exception", "User", "CustomData") VALUES (            TO_TIMESTAMP_TZ(:timestamp, 'YYYY-MM-DD HH24:MI:SS.FF3'), :loglevel, :whichlogger, :message, :whatexception, :userx, :customdata)</commandText><parameter name=":timestamp" layout="${date:format=yyyy-MM-dd HH\:mm\:ss.fff}" /><parameter name=":loglevel" layout="${level}" /><parameter name=":whichlogger" layout="${logger}" /><parameter name=":message" layout="${message:raw=true}" /><parameter name=":whatexception" layout="${exception:tostring}" /><parameter name=":userx" layout="${event-properties:item=userx}" /><parameter name=":customdata" layout="${event-properties:item=customdata}" /></target><target name="consoleTarget" xsi:type="ColoredConsole" layout="${longdate} ${uppercase:${level}} ${message} ${all-event-properties}" /></targets><extensions><add assembly="NLog.Database"/><add assembly="NLog.Web.AspNetCore"/></extensions><rules><logger name="DatabaseLogger" minlevel="Trace" writeTo="dataBaseTarget" /><logger name="ConsoleLogger" minlevel="Trace" writeTo="consoleTarget" /></rules>

How can i add both Loggers to the ServiceCollection using the builder like this?

builder.Logging.ClearProviders();builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);builder.Host.UseNLog(new NLogAspNetCoreOptions()); //default options

And how can I inject both of them to my Services and use them both (for different logmessages)?

private readonly ILogger<MyService> _databaselogger;private readonly ILogger<MyService> _consoleLogger;public MyService(ILogger<MyService> databaselogger, ILogger<MyService> consoleLogger) //how to distinguish the loggers?{    _databaselogger = databaselogger;    _consoleLogger = consoleLogger;    _databaseLogger.LogInformation("This logmessage is written to the database");    _consoleLogger.LogInformation("This logmessage is written to the console");}

Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>