logo
Tags down

shadow

Memory leak in .NET Core 3.0 app when using NLog or Serilog


By : Leo
Date : September 15 2020, 09:00 AM
Any of those help I have also noticed high memory consumption. There have been a few different things to try including:
using .Destructure.ToMaximumCollectionCount(10) // Default is int.MaxValue removing .Enrich.WithExceptionDetails to see if the memory issue magically disappears Checking the Swap file memory usage of the Linux container and hence setting the Swapiness value (although take care of unintended consequences)
code :


Share : facebook icon twitter icon

Does ASP.NET Core's built-in logging make NLog/Serilog/etc obsolete?


By : nikitabarnawal
Date : March 29 2020, 07:55 AM
this will help The ASP.NET logging is a common (logging) interface and log implementation.
You could use the common interface and 3rd party library (e.g NLog) together as the infrastructure is prepared for that.

Nlog Error when writing to database, what is the correct config for Nlog in asp core 2?


By : Sweekriti Satpathy
Date : March 29 2020, 07:55 AM
seems to work fine Solved by,
adding connectionString="${var:ConnectionStrings}" , and including
code :
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            env.ConfigureNLog("nlog.config");

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
                app.UseDatabaseErrorPage();

            }
            else
            {
                app.UseExceptionHandler("/Error");
            }
            app.UseStaticFiles();
            app.UseAuthentication();
            loggerFactory.AddNLog();
            app.AddNLogWeb();
            LogManager.Configuration.Variables["ConnectionStrings"] = Configuration.GetConnectionString("ARTCore");
            LogManager.Configuration.Variables["configDir"] = "D:\\SQLCORE\\RazorCore\\ArtCore\\ArtCore\\Logs";
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });
        }
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      keepVariablesOnReload="true"
      internalLogLevel="Warn"
      throwExceptions="false"
      internalLogFile="D:\SQLCORE\RazorCore\ArtCore\ArtCore\Logs\internal-nlog.txt">
  <targets>
    <target xsi:type="File" name="allfile" fileName="${var:configDir}\nlog-all.log"
                    layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />

    <target xsi:type="File" name="ownFile-web" fileName="${var:configDir}\nlog-own.log"
             layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|  ${message} ${exception}" />

    <target xsi:type="Null" name="blackhole" />
    <target name="ARTCore" xsi:type="Database" connectionString="${var:ConnectionStrings}" >
      <commandText>
        insert into dbo.Log (
        Application, Logged, [Level], Message,
        Logger, CallSite, Exception
        ) values (
        @Application, @Logged, @Level, @Message,
        @Logger, @Callsite, @Exception
        );
      </commandText>
      <parameter name="@application" layout="AspNetCoreNlog" />
      <parameter name="@logged" layout="${date}" />
      <parameter name="@level" layout="${level}" />
      <parameter name="@message" layout="${message}" />
      <parameter name="@logger" layout="${logger}" />
      <parameter name="@callSite" layout="${callsite:filename=true}" />
      <parameter name="@exception" layout="${exception:tostring}" />
    </target>
  </targets>
  <rules>
    <logger name="*" minlevel="Trace" writeTo="allfile" />
    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" /> 
    <logger name="*" minlevel="Trace" writeTo="ARTCore" />
  </rules>
</nlog>

Can Serilog ForContext cause memory leak?


By : John
Date : March 29 2020, 07:55 AM
will be helpful for those in need No, calling ILogger.ForContext()is not known to be a memory leak risk - Serilog does not keep any references to the returned logger object.

Redirect all NLog output to Serilog with a custom Target


By : Bo Yuan
Date : March 29 2020, 07:55 AM
I hope this helps you . I think the best option is indeed a custom NLog target. Something like this: (C#)
code :
using NLog;
using NLog.Targets;
using Serilog;
using Serilog.Events;

namespace MyNamespace
{
    [Target("SerilogTarget")]
    public sealed class SerilogTarget : TargetWithLayout
    {
        protected override void Write(LogEventInfo logEvent)
        {
            var log = Log.ForContext(Serilog.Core.Constants.SourceContextPropertyName, logEvent.LoggerName);
            var logEventLevel = ConvertLevel(logEvent.Level);
            if ((logEvent.Parameters?.Length ?? 0) == 0)
            {
                // NLog treats a single string as a verbatim string; Serilog treats it as a String.Format format and hence collapses doubled braces
                // This is the most direct way to emit this without it being re-processed by Serilog (via @nblumhardt)
                var template = new Serilog.Events.MessageTemplate(new[] { new Serilog.Parsing.TextToken(logEvent.FormattedMessage) });
                log.Write(new Serilog.Events.LogEvent(DateTimeOffset.Now, logEventLevel, logEvent.Exception, template, Enumerable.Empty<Serilog.Events.LogEventProperty>()));
            }
            else
                // Risk: tunneling an NLog format and assuming it will Just Work as a Serilog format
#pragma warning disable Serilog004 // Constant MessageTemplate verifier
                log.Write(logEventLevel, logEvent.Exception, logEvent.Message, logEvent.Parameters);
#pragma warning restore Serilog004
        }

        static Serilog.Events.LogEventLevel ConvertLevel(LogLevel logEventLevel)
        {
            if (logEventLevel == LogLevel.Info)
                return Serilog.Events.LogEventLevel.Information;
            else if (logEventLevel == LogLevel.Trace)
                return Serilog.Events.LogEventLevel.Verbose;
            else if (logEventLevel == LogLevel.Debug)
                return Serilog.Events.LogEventLevel.Debug;
            else if (logEventLevel == LogLevel.Error)
                return Serilog.Events.LogEventLevel.Error;
            return Serilog.Events.LogEventLevel.Fatal;
        }
    }
}
// Register so it can be used by config file parsing etc
Target.Register<MyNamespace.SerilogTarget>("SerilogTarget"); 
    public static void ReplaceAllNLogTargetsWithSingleSerilogForwarder()
    {
        // sic: blindly overwrite the forwarding rules every time
        var target = new SerilogTarget();
        var cfg = new NLog.Config.LoggingConfiguration();
        cfg.AddTarget(nameof(SerilogTarget), target);
        cfg.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Trace, target));
        // NB assignment must happen last; rules get ingested upon assignment
        LogManager.Configuration = cfg;
    }
module SerilogHelpers =

    let private mapLevel = function
        | x when x = NLog.LogLevel.Info -> LogEventLevel.Information
        | x when x = NLog.LogLevel.Off || x = NLog.LogLevel.Trace -> LogEventLevel.Verbose
        | x when x = NLog.LogLevel.Debug -> LogEventLevel.Debug
        | x when x = NLog.LogLevel.Warn -> LogEventLevel.Warning
        | x when x = NLog.LogLevel.Error ->  LogEventLevel.Error
        | _ -> LogEventLevel.Fatal

    // via https://stackoverflow.com/a/49639001/11635
    [<NLog.Targets.Target("SerilogTarget")>]
    type SerilogTarget() =
        inherit NLog.Targets.Target()

        static member InitializeAsGlobalTarget() =
            // sic: blindly overwrite the forwarding rules every time
            // necessary as Azure Startup establishes a different config as a bootstrapping step
            // see: LogModule.To.target("rollingFile", create, "*", LogLevel.Trace)
            let cfg, target = NLog.Config.LoggingConfiguration(), SerilogTarget()
            cfg.AddTarget("SerilogTarget", target)
            cfg.LoggingRules.Add(NLog.Config.LoggingRule("*", NLog.LogLevel.Trace, target))
            // NB assignment must happen last; rules get ingested upon assignment
            NLog.LogManager.Configuration <- cfg

        override __.Write(logEvent : NLog.LogEventInfo) =
            let log = Log.ForContext(Serilog.Core.Constants.SourceContextPropertyName, logEvent.LoggerName)
            match logEvent.Parameters with
            | xs when isNull xs || xs.Length = 0 ->
                // NLog treats a single string as a verbatim string; Serilog treats it as a String.Format format and hence collapses doubled braces
                // This is the most direct way to emit this without it being re-processed by Serilog (via @nblumhardt)
                let template = MessageTemplate [| Serilog.Parsing.TextToken(logEvent.FormattedMessage) |]
                log.Write(new LogEvent(DateTimeOffset.Now, mapLevel logEvent.Level, logEvent.Exception, template, Seq.empty<LogEventProperty>))
            | _ ->
                // Risk: tunneling an NLog format and assuming it will Just Work as a Serilog format
                log.Write(mapLevel logEvent.Level, logEvent.Exception, logEvent.Message, logEvent.Parameters)

How to Log to Elastic Search by NLog or SeriLog with authentications


By : acep saepul
Date : March 29 2020, 07:55 AM
it helps some times Since you want to log into ElasticSearch, it's best if you use a Logging framework that supports Structured Logging which for [NLog] this feature is in beta RTM.
You can Serilog as your Logging Framework which supports Structured Logging.
code :
Serilog
Serilog.Sinks.ElasticSearch  
var logger = new LoggerConfiguration()
    .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200"))
    {
        ModifyConnectionSettings = x => x.SetBasicAuthentication(username, password);
    })
    .CreateLogger();
Related Posts Related Posts :
  • SQL Command Parameter cannot covert string to int
  • Azure Notification Hub example to register a device and receive a notification
  • Disabed element shown as enabled in Selenium C#
  • Html.listboxfor() how to capture event on change/add item - Jquery MVC (C#)
  • c# Accessing my array inside a class constructor
  • How to first 'Split a string to an Array' then 'Add something to that Array'? || C# Console App
  • IEnumerable of Tuple of string of string
  • Why don't I get a warning about possible dereference of a null in C# 8 with a class member of a struct?
  • Visual Studio 2019: how to disable specific CodeAnalysis messages in .editorconfig?
  • Pass ID to controller on prev or next
  • What are the difference using app.run and app.useendpoints in asp.net-core?
  • Why string Method(Object object) may not match Func<Object, string> delegate type?
  • Check inside loop if *txt file has been created
  • C# retry logic While loop
  • Convert object {object[]} to string[]
  • Difference between initialize a string to "" or to "".ToString() - Which one should I use?
  • How to make the console wait but then continue without pressing a Key?
  • extract text in rich text format from range
  • how to handle 1000 concurrent user requests per second in asp.net web api
  • In C# How to get Windows Credentials from credential manager
  • Override default value of null conditional operator
  • How to fix override ToString method
  • System.IO.FileNotFoundException when creating EF migrations on .net core
  • Login limit attempts in C#
  • Loop into ListView elements
  • Changing Blazor folder gives me "Cannot find the fallback endpoint"
  • creating class from JSON with different types of a node
  • How to define models for Database tables in C# without using Linq To DB?
  • Understanding Identityserver4 with Identity (cookies/tokens, server architecture)
  • How to Deserialize a JSON into a list using SIMPLE JSON?
  • another option instead using AsEnumerable() in linq EF, when using custom method in linq
  • Parameterized query that returns TEXT column(s) always returns zero for INT columns
  • Why format is not working while appending zeros?
  • SqlConnection string
  • Entity Framework Core Update Database - Code First Approach Without Migration
  • Unity Update Method
  • Custom Middleware is causing Blazor Server-side page to stop working
  • Declaring hex number: The name 'B9780' does not exist in the current context
  • Invalid cast from 'System.Int32' to Enum using reflections
  • Why does my webrequest line need updating? (error (426) Upgrade Required )
  • How to generate Key and Key IV aes in C#
  • How can I display view inside content control in wpf
  • How can I wait for form2 to finish?
  • Is Application.DoEvents() a form of Multitasking?
  • In C#, how can I see if the first character in an account is a specific value?
  • C# Determine if a char at index is between two characters in a string
  • C# - Winform Timer - Disposing and emptying the timer
  • if else condition in Regex c# and return constant value
  • Ternary operator for 3 conditions
  • Fineuploader with Azure, Empty image problem
  • How do I unit test the event raised by class under test?
  • How to set up .net core service that uses a generic repository
  • ASP.NET Core 3.0 Endpoint Routing doesn't work for default route
  • use gmail API token on localhost and hosting at the same time
  • Try-catch FormatException
  • why do sql procedure retuns 0 rows when called from applciation?
  • .Net core 3: The namespace internal does not exist in Microsoft.Extensions.Logging.Internal
  • how to interpolate a variable into string method
  • I want to instantiate an object at the location of another object which is destroyed
  • How to display full path of ALL currently running process in C#?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk