Code Monkey home page Code Monkey logo

nlogviewer's Introduction

Nuget

NuGet NuGetDownloads

A NuGet-package is available here.

NlogViewer

NlogViewer is a ui control library to visualize NLog logs in your personal application. It is mainly based on Sentinel and its controls.

supported Framework: .NET6

NLogViewer

Quick Start

Add a namespace to your Window

xmlns:dj="clr-namespace:DJ;assembly=NLogViewer"

use the control

<dj:NLogViewer/>

NlogViewer is subscribing to CacheTarget. By default, the NlogViewer is automatically creating a CacheTarget with loggingPattern "*" and LogLevel "Trace".

If you want to customize the loggingPattern and LogLevel, add the following to your Nlog.config.

<?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"
  xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
  autoReload="true">

  <extensions> 
    <add assembly="NLogViewer"/> 
  </extensions> 

  <targets async="true">
    <target
      xsi:type="CacheTarget"
      name="cache"/>
  </targets>

  <rules>
    <logger name="*" writeTo="cache" minlevel="Debug"/> 
  </rules>
</nlog>

Customize

Colors

Customize foreground or background of every logLevel

NLogViewer

Multi targeting

Use more than one instance of NLogViewer to match different rules.

Create 2 targets with their own rules.

<targets async="true">
  <target xsi:type="CacheTarget" name="target1"/>
  <target xsi:type="CacheTarget" name="target2"/>
</targets>

<rules>
  <logger name="*" writeTo="target1" maxlevel="Info"/> 
  <logger name="*" writeTo="target2" minlevel="Warn"/> 
</rules>

Set TargetName property to link them.

<dj:NLogViewer TargetName="target1"/>
<dj:NLogViewer TargetName="target2"/>

Format output (ILogEventInfoResolver)

To format the output of a LogEventInfo, implement a new instance of ILogEventInfoResolver and bind it to the Resolver you want to customize:

/// <summary>
/// Reformat the DateTime
/// </summary>
public class FooTimeStampResolver : ILogEventInfoResolver
{
    public string Resolve(LogEventInfo logEventInfo)
    {
        return logEventInfo.TimeStamp.ToUniversalTime().ToString();
    }
}
NLogViewer1.TimeStampResolver = new FooTimeStampResolver();

Samples

open on a new window

NLogViewer

Create a new Window and add a default NLogViewer

<dj:NLogViewer TargetName="target1"/>

Open the new Window

TestPopup popup = new TestPopup();
popup.Show();

seperate logger for a task

NLogViewer

Below is a sample how you could create a NLogViewer for a task

// create unique target name
var taskNumber = _RandomTaskCounter++;
string targetName = $"task{taskNumber}";
// create a unique logger
var loggerName = $"MyFoo.Logger.{taskNumber}";
var logger = LogManager.GetLogger(loggerName);

// create new CacheTarget
CacheTarget target = new CacheTarget
{
    Name = targetName
};

// get config // https://stackoverflow.com/a/3603571/6229375
var config = LogManager.Configuration;

// add target
config.AddTarget(targetName, target);

// create a logging rule for the new logger
LoggingRule loggingRule = new LoggingRule(loggerName, LogLevel.Trace, target);

// add the logger to the existing configuration
config.LoggingRules.Add(loggingRule);

// reassign config back to NLog
LogManager.Configuration = config;

// create a new NLogViewer Control with the unique logger target name
NLogViewer nLogViewer = new NLogViewer
{
    TargetName = targetName,
};

// add it to the tab control
var tabItem = new TabItem { Header = $"Task {taskNumber}", Content = nLogViewer };
TabControl1.Items.Add(tabItem);
TabControl1.SelectedItem = tabItem;

// create task which produces some output
var task = new Task(async () =>
{
    while (true)
    {
        logger.Info($"Hello from task nr. {taskNumber}. It's {DateTime.Now.ToLongTimeString()}");
        await Task.Delay(1000);
    }
});

Why CacheTarget?

There is already a NLogViewerTarget, which is used for Sentinel. See here

<target 
    xsi:type="NLogViewer"
    name="sentinel"
    address="udp://127.0.0.1:9999"/>

Contributors

Feel free to make a PullRequest or open an Issue to extend this library!

nlogviewer's People

Contributors

djonasdev avatar dependabot-preview[bot] avatar dependabot[bot] avatar kwhrkzk avatar

Stargazers

Austin Rafuls avatar  avatar  avatar  avatar  avatar  avatar  avatar Bevjfweoew avatar Mike.Zhao avatar  avatar Flithor avatar MichaelO avatar  avatar Vlad Sarpe avatar  avatar Elvis Wang avatar Mumtaz Malik avatar Neoasis Werx avatar Vishwa Theja Pokala avatar jimifish avatar fred avatar  avatar Thomas Galliker avatar KleinPan avatar  avatar  avatar Jeffrey avatar  avatar  avatar Itarci José Possamai avatar  avatar  avatar  avatar  avatar Stanislav Mursaev avatar  avatar maohuiqiang avatar  avatar Kaizhi Xuan avatar  avatar b-wind avatar Aijkl avatar losttem avatar  avatar Linh Peach avatar Karen Payne avatar  avatar Alexander avatar  avatar Daniel Meza avatar Terje avatar skyarea avatar EmmeFreeze avatar Alexander Prokhorov avatar 洛洛 avatar Yan Han avatar Carlito avatar evrstr avatar Jens De Cock avatar  avatar  avatar  avatar owen229 avatar Dandelion avatar  avatar James Pereira avatar zhangx avatar Fumihiro Kojima avatar Rodion Chaykovskiy avatar Dani John avatar Kim Taehwan avatar SoftExpert avatar Kenzo avatar supermomonga avatar  avatar Petr Palas avatar Matthew Wilkinson avatar Crusty Applesniffer avatar Dovydas M avatar Mark Nuzz avatar Monte Jones avatar RoyLai avatar  avatar  avatar  avatar

Watchers

James Cloos avatar SoftExpert avatar  avatar  avatar

nlogviewer's Issues

implement custom message resolver

Actually only LogEvent.Message is printed to the Control.Message column.

If you don't use a custom LayoutRenderer to manipulate/customize your output, it should be possible to override the output.

include PDB files in nuget package / snupkg

Add following to the directory.build.props

<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>

snupkg should be pushed to the nuget.org server. Additionally the pdbs files will be included in the nupkg if u need it local

TestApp appears to white after application start

I'm having issues with this in my app resizing my window to go across all three monitors. I tried running the example in Master, but it doesn't seem to run very well - it doesn't display two logs and after a couple seconds the whole application goes white. Is the demo stable?

Each entry uses up too much memory and clear doesn't clear memory used.

This might need to be two issue reports but both relate to memory usage.

I found that the application was eating ~300MB at 500 entries and 6.5GB of memory at 23000 entries.

To quickly reproduce, change this line in TestApp MainWindow.cs:

Observable.Interval(TimeSpan.FromMilliseconds(10)).ObserveOnDispatcher().Subscribe(l =>

Also, the Pause button stops the addition of new log entries and pauses the memory growth. However, the Clear command clears the shown log entries but does not clear the memory used thus creates a memory leak.

[Edit]I re-ran the app with just 100 entries (Take(100)) which settled at roughly 69.3MB with a start memory of 27.8MB (before any entries). This generates 41.5MB for 100 records.

Implementing in code (not nlog.confg)

I've been wrestling with implementing this for the past little while (trying to adapt the instructions for nlog.config to their in-code equivalents) but can't seem to get it right.

In particular, I'm struggling with the equivalents for:

Do you have any pointers? I've been looking through the NLog documentation and searching online for a bit but haven't found much help except for that link regarding the assembly loading.

ParentWindow is null

can you please check if the Parentwindow is null ?

If I add the UserControl as an ElementHost child (e.g. in my Outlook Addin) then it'll throw me an exception, because it is not loaded in a Window...

here:
if (_ParentWindow.FindChildByUid(Uid) == null)
and here:
_ParentWindow.Closed += _ParentWindowOnClosed;

Thanks

NLogViewer not updating its visual components

Hello,

I have a TabControl with various tabs, which will be added dynamically. Each tab has a NLogViewer for displaying logs happening inside that tab. Your sample code works great when added inside xaml, but when added via code, the following behaviour occurs:
If switched between tabs, the initial tab, which holds a programmatically created NLogViewer, is not updating its visual components compared to tabs which hold a NLogView created inside the xaml.

This is my code, to create the controls and other stuff:

LoggingConfiguration config = LogManager.Configuration;

var logger = LogManager.GetLogger(LoggerName);


CacheTarget target = new CacheTarget()
{
    Name = LoggerName
};
config.AddTarget(LoggerName, target);

LoggingRule loggingRule = new LoggingRule("*", LogLevel.Trace, target);

loggingRule.DefaultFilterResult = FilterResult.Ignore;
loggingRule.Filters.Add(new WhenEqualFilter()
{
    Layout = "${logger}",
    CompareTo = LoggerName,
    Action = FilterResult.Log,
    IgnoreCase = true
});

config.LoggingRules.Add(loggingRule);

LogManager.Configuration = config;

NLogViewer_ = new NLogViewer()
{
    TargetName = LoggerName,
};

TabItemLog.Content = NLogViewer_;


Task t = Task.Run(() =>
{
    for (int k = 0; k < 10000; k++)
    {
        logger.Error("error: " + k + " || " + LoggerName);
        Thread.Sleep(1000);
    }
});

TabControl incompatibility (1.2.0)

When i smash my NLogViewer instance into the Content of a TabItem (of a TabControl),
whenever i re-open the tab, NlogViewer seems to create additional nlog-targets, and then shows all messages multiple times. increasing exponentially on each re-open.

this bug seems to be introduced in 1.2.0, i don't remember noticing this behaviour before.

maybe helpful: the Loaded event of TabItem's get called on each re-opening of that tab. This differs from the Window Loaded event behaviour

Fix message column crop bug

Based on this PR #6

Actually the message column is to small on default. A mechanism must be implemented to automatically enlarge the column to the maximum available width.

implement git workflow

  • Add workflow for build and deploy pipeline
  • Automatically push nuget packages
  • Manual trigger pre-releases

Roadmap

  • Implement NLogViewer.Server
  • Implement NLogViewer.Webinterface
  • Implement NLogViewer.ClientApplication

NLogViewer.Server

.NET server application which can handle the NLogViewerTarget (https://github.com/NLog/NLog/wiki/NLogViewer-target) and provides the NLogViewer.Webinterface

NLogViewer.Webinterface

Provides an extension method to add an webinterface to your .NET Server application.

Example call in your Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
	app.UseNlogViewerWebinterface(new NLogViewerWebinterfaceOptions()
	{
		Path = "/nlogviewer"
	});
}

NLogViewer.ClientApplication

Standalone application which can handle the NLogViewerTarget.


Please feel free to contribute

Performance Issue - Cache tooks long time

In my case I have used both CacheTarget & FileTarget

In my case I will add 20-30k logs after that I will show some results view window.
So my tasks are completed and logs are added in files and then results are shown
But In CacheTarget, it took longer time atmost 20m for me.
Due to that I can't properly see the logs on UI NLogViewer.

Thanks

upgrade to .net 5.0 breaks because of System.Reactive

when upgrading my project to .net 5.0 I encountered an issue with the new version of System.Reactive.
System.TypeLoadException: 'Could not load type 'System.Reactive.Linq.DispatcherObservable' from assembly 'System.Reactive, Version=5.0.0.0, Culture=neutral, PublicKeyToken=94bc3704cddfc263'.'

Susbscription dispose when undock the viewer parent container.

When the component is set on an Doking system like RadDocking on telerik, when the pane is undock from the main windows the log stop working, this is caused by the _Subscription disposition of the viewer.

I know that this is an expected behavior because we want to stop listen for new logs when the windows is closed, or unloaded, but the issue cause that the viewer dons't start to listen again whe the new windows set or even when the current windows loads again, and since the control dons't has any recovery strategy to start listen again, it fall in a useless state.

To solve this issue we should separete the log subscription login on two main public method:

StartListen();
This method should start listen the log by subscribing to the cache, and should be called in the current _OnLoaded even handler in order to keep the same functionality and start Listen as soon as the windows loads.

StopListen();

This method should stop the listen subscription for new logs as happen now in the _OnUnloaded event handler, and also should be called from the same hadler to keep the functionality.

Whit this 2 methods the user can start again to listen for new logs in such scenarios like the docking windows or any future scenario that require Start/Stop listen for logs.

Even the pause functionality could be promoted to use this method in order to improve performance.

I open this discussion, @dojo90 if you agree I could start a PR

Does it possible to create NLogViewer targets entities dynamically?

Hi,

I would like to create a tab control dynamically each time that a user for example download a file, this tab will include the log associated only to this task.

How can I create and isolate logs programmatic from each of these items inserted in a controller and logs trace separately?

Any help or example about how to consume logs dynamically/programmatically for at least 2 entities would be appreciated.

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.