Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NLog MemoryTarget maximum size

Tags:

nlog

Since I have a global exception handler that reports uncaught errors via e-mail, next step is to add some context to it by having some 10-20 last lines of log that are collected.

So I am using MemoryTarget like so:

MemoryTarget _logTarget;
_logTarget = new MemoryTarget();
_logTarget.Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}${exception}";
LoggingRule loggingRule = new LoggingRule("*", LogLevel.Debug, _logTarget);
LogManager.Configuration.AddTarget("exceptionMemory", _logTarget);
LogManager.Configuration.LoggingRules.Add(loggingRule);
LogManager.Configuration.Reload();

Apps containing this should run forever, and if I leave logs in memory, unchecked, I'll have neatly designed memory leak.

How to address this? How to truncate MemoryTarget.Logs to have at most say 100 lines?

like image 687
Daniel Mošmondor Avatar asked May 17 '26 21:05

Daniel Mošmondor


1 Answers

Your best bet is probably to write your own MemoryTarget... Something like this (untested) should work.

namespace NLog.Targets
{
    using System.Collections.Generic;

    [Target("LimitedMemory")]
    public sealed class LimitedMemoryTarget : TargetWithLayout
    {
        private Queue<string> logs = new Queue<string>();

        public LimitedMemoryTarget()
        {
            this.Logs = new List<string>();
        }

        public IEnumerable<string> Logs 
        { 
          get { return logs; }
          private set { logs = value; }
        }

        [DefaultValue(100)]
        public int Limit { get; set; }

        protected override void Write(LogEventInfo logEvent)
        {
            string msg = this.Layout.Render(logEvent);

            logs.Enqueue(msg);
            if (logs.Count > Limit)
            {
              logs.Dequeue();
            }    
        }
    }
}

This example is based on the NLog MemoryTarget, the source code for which you can find here:

https://github.com/NLog/NLog

NLog docs are here:

http://nlog-project.org/documentation/v2.0.1/

I didn't see anything like you are asking about in either location.

like image 163
wageoghe Avatar answered May 20 '26 22:05

wageoghe