Giter Site home page Giter Site logo

nlog.windows.forms's Introduction

NLog.Windows.Forms

Version AppVeyor codecov.io

This package provides NLog Targets that redirect logging output to Windows Forms:

See list

Register Extension

Install the NLog.Windows.Forms NuGet package and register the extension-assembly.

NLog will only recognize the extensions when loading from NLog.config-file, by adding the extension to NLog.config-file:

<extensions>
  <add assembly="NLog.Windows.Forms"/>
</extensions>

Alternative register from code using fluent configuration API:

NLog.LogManager.Setup().RegisterWindowsForms();

nlog.windows.forms's People

Contributors

304notmodified avatar dependabot-preview[bot] avatar dependabot[bot] avatar fr33dan avatar kichristensen avatar mikhail-barg avatar snakefoot 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nlog.windows.forms's Issues

Target support for .net core 3.0

Warning NU1701 Package 'NLog.Windows.Forms 4.2.3' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v3.0'. This package may not be fully compatible with your project.

Fix EOL normalization

after .gitattributes has been changed:

rm .git/index     # Remove the index to force git to
git reset         # re-scan the working directory
git status        # Show files that will be normalized
git add -u
git commit -m "EOL normalization"

See #17

related NLog/NLog#752

Using Only NLog.config for RichTextBox Does Not Log

Hello! I'm trying to log to a RichTextBox by setting up my logger only through the NLog.config file by trying to run the RichTextBox.sln with the following lines commented out of Form1.cs

private void Form1_Load(object sender, EventArgs e)
        {
            // Programmatic configuration that is equivalent to
            // the "richTextBox" target configuration in NLog.config
            //RichTextBoxTarget target = new RichTextBoxTarget();
            //target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            //target.ControlName = "richTextBox1";
            //target.FormName = "Form1";
            //target.UseDefaultRowColoringRules = true;

            //NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);

            Logger logger = LogManager.GetLogger("Example");
            logger.Trace("trace log message");
            logger.Debug("debug log message");
            logger.Info("info log message");
            logger.Warn("warn log message");
            logger.Error("error log message");
            logger.Fatal("fatal log message");
        }`

If I'm understanding correctly, commenting out the top-half of this method should prevent the NLog.config from being overwritten by the new programmatically defined config. However, the outcome of this (at least on my system) is that nothing shows up in the RichTextBox at all. These comments are the only changes I've made to the code, otherwise it is exactly the same as what's in the master branch. Can RichTextBoxTarget only be setup programmatically? If you need any more information, let me know.

Thank you!

PublishSingleFile causes Target symbol-name is unknown: 'RichTextBox'

Hello,

I use NLog.Windows.Forms (version 4.5.0).
Whenever a Project is published with this property:

<PublishSingleFile>true</PublishSingleFile>

I get such an error: (internalLogfile.log)

Info Message Template Auto Format enabled
Info Adding target FileTarget(Name=logfile)
Warn Error has been raised. Exception: NLog.NLogConfigurationException: Failed to create Target of type: RichTextBox
 ---> System.ArgumentException: Target symbol-name is unknown: 'RichTextBox'
   at NLog.Config.Factory`2.CreateInstance(String itemName)
   at NLog.Config.LoggingConfigurationParser.FactoryCreateInstance[T](String classType, INamedItemFactory`2 factory)
   --- End of inner exception stack trace ---
Warn Error has been raised. Exception: NLog.NLogConfigurationException: Failed to create Target of type: RichTextBox
 ---> System.ArgumentException: Target symbol-name is unknown: 'RichTextBox'
   at NLog.Config.Factory`2.CreateInstance(String itemName)
   at NLog.Config.LoggingConfigurationParser.FactoryCreateInstance[T](String classType, INamedItemFactory`2 factory)
   --- End of inner exception stack trace ---
Warn Error has been raised. Exception: NLog.NLogConfigurationException: Target 'warningControl' not found for logging rule: *.
Warn Error has been raised. Exception: NLog.NLogConfigurationException: Target 'logControl' not found for logging rule: *.
Info Validating config: TargetNames=logfile, ConfigItems=23, FilePath=D:\development\branches\EFA_10_5\realtime\Solutions\DDIP\Applications\Mdv.DDIP.BatchWork.GUI\bin\release\win-x64\publish\NLog.config
Info Configuration initialized.
Info NLog, Version=5.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: . Product version: . GlobalAssemblyCache: False
Info Executing ReInitializeAllTextboxes for Form Mdv.Realtime.BatchWork.GUI.MainWindow, Text: DDIP v.10.5.8.1 Batch work GUI [new]
Info Configuring from an XML element in D:\development\branches\EFA_10_5\realtime\Solutions\DDIP\Applications\Mdv.DDIP.BatchWork.GUI\bin\release\win-x64\publish\NLog.config...
Info Message Template Auto Format enabled
Info Adding target FileTarget(Name=logfile)
Warn Error has been raised. Exception: NLog.NLogConfigurationException: Failed to create Target of type: RichTextBox
 ---> System.ArgumentException: Target symbol-name is unknown: 'RichTextBox'
   at NLog.Config.Factory`2.CreateInstance(String itemName)
   at NLog.Config.LoggingConfigurationParser.FactoryCreateInstance[T](String classType, INamedItemFactory`2 factory)
   --- End of inner exception stack trace ---
Warn Error has been raised. Exception: NLog.NLogConfigurationException: Failed to create Target of type: RichTextBox
 ---> System.ArgumentException: Target symbol-name is unknown: 'RichTextBox'
   at NLog.Config.Factory`2.CreateInstance(String itemName)
   at NLog.Config.LoggingConfigurationParser.FactoryCreateInstance[T](String classType, INamedItemFactory`2 factory)
   --- End of inner exception stack trace ---
Warn Error has been raised. Exception: NLog.NLogConfigurationException: Target 'warningControl' not found for logging rule: *.
Warn Error has been raised. Exception: NLog.NLogConfigurationException: Target 'logControl' not found for logging rule: *.
Info Validating config: TargetNames=logfile, ConfigItems=23, FilePath=D:\development\branches\EFA_10_5\realtime\Solutions\DDIP\Applications\Mdv.DDIP.BatchWork.GUI\bin\release\win-x64\publish\NLog.config
Info AppDomain Shutting down. LogFactory closing...
Info LogFactory has been closed.

I tried the following package constellations:

Nlog 5.0.0-rc2
Nlog.Windows.Forms 4.5.0

and

NLog 4.7.0
Nlog.Windows.Forms 4.5.0-rc1

In case I build the project without this PublishSingleFile property, the logging into RichTextBox works fine.

Fix default layout comments

 /// <remarks>
        /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
        /// </remarks>

NLog.LogManager.Configuration reload causes RichTextBoxTarget to create a new form

Hi! Thanks for reporting this bug!

Please keep / fill in the relevant info from this template so that we can help you as best as possible.

NLog version: (5.4)

Platform: ..Net 4.5

LoggingConfiguration config = new LoggingConfiguration();

config.AddRule(LogLevel.Info, LogLevel.Fatal, new RichTextBoxTarget
{
    TargetRichTextBox = richTextBox1,
    MaxLines = 50,

}, "*");


NLog.LogManager.Configuration = config;
var logger1 = NLog.LogManager.GetCurrentClassLogger();
logger1.Info("test1");
//this make 'test2' been put out in a new form
NLog.LogManager.Configuration = NLog.LogManager.Configuration;
logger1.Info("test2");

--‘test2’ been out put in a new form instead of richTextBox1 while using 'NLog.LogManager.Configuration = NLog.LogManager.Configuration'
image

License inconsistency

Hi, I'm testing NLog to replace a self written log engine and wanted to use NLog.Windows.Forms. But I'm a little bit confused about its license:
NLog is BSD licenses. But NLog.Windows.Forms is licensed under GPLv2. But some source files like FormControlTarget.cs and FormHelper.cs are ALv2 licensed.
It would be nice if you can make the licenses consistent. Ideally for me change it to BSD as at NLog.

nlog richtextbox - Target cannot be found: 'RichTextBox'

I created a question on stack overflow:
[(http://stackoverflow.com/questions/37600639/nlog-richtextbox-target-cannot-be-found-richtextbox)]

The details are copied below?

I had this working, but I tried to update nlog and use the nuget packages, including NLog.Windows.Forms.

Now I am getting NLog.NLogConfigurationException with the inner exception:

Target cannot be found: 'RichTextBox'

The project references both: NLog and NLog.Windows.Forms

from packages.config:

  <package id="NLog" version="4.3.4" targetFramework="net46" />
  <package id="NLog.Config" version="4.3.4" targetFramework="net46" />
  <package id="NLog.Schema" version="4.3.4" targetFramework="net46" />
  <package id="NLog.Windows.Forms" version="4.2.3" targetFramework="net46" />

from nlog.config

<target name="rtb" xsi:type="RichTextBox" controlName="RichTextBox1" formName="NewForm"
        useDefaultRowColoringRules="true" layout="[${date}] [${level:uppercase=true}] [${logger}] ${message}" />



<logger name="*" minlevel="Trace" writeTo="file,rtb" />

Adding internal logging didn't seem to give much more information:

...
2016-06-03 06:17:23.9385 Trace Scanning MessageLayoutRenderer 'Layout Renderer: ${message}'
2016-06-03 06:17:23.9550 Info Adding target File Target[file]
2016-06-03 06:17:23.9550 Debug Registering target file: NLog.Targets.FileTarget
2016-06-03 06:17:23.9550 Error Error in Parsing Configuration File. Exception: NLog.NLogConfigurationException: Exception occurred when loading configuration from C:\Users\Derek.Morin\Documents\Visual Studio 2010\Projects\ScriptCode\ScriptCode.ConvertedToC#\bin\x86\Debug\NLog.config ---> System.ArgumentException: Target cannot be found: 'RichTextBox'
   at NLog.Config.Factory`2.CreateInstance(String name)
   at NLog.Config.XmlLoggingConfiguration.ParseTargetsElement(NLogXmlElement targetsElement)
   at NLog.Config.XmlLoggingConfiguration.ParseNLogElement(NLogXmlElement nlogElement, String filePath, Boolean autoReloadDefault)
   at NLog.Config.XmlLoggingConfiguration.ParseTopLevel(NLogXmlElement content, String filePath, Boolean autoReloadDefault)
   at NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader, String fileName, Boolean ignoreErrors)
   --- End of inner exception stack trace ---
2016-06-03 06:17:23.9700 Error Error has been raised. Exception: System.ArgumentException: Target cannot be found: 'RichTextBox'
   at NLog.Config.Factory`2.CreateInstance(String name)
   at NLog.Config.XmlLoggingConfiguration.ParseTargetsElement(NLogXmlElement targetsElement)
   at NLog.Config.XmlLoggingConfiguration.ParseNLogElement(NLogXmlElement nlogElement, String filePath, Boolean autoReloadDefault)
   at NLog.Config.XmlLoggingConfiguration.ParseTopLevel(NLogXmlElement content, String filePath, Boolean autoReloadDefault)
   at NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader, String fileName, Boolean ignoreErrors)

If I can't get an answer for how to get it working with the nlog.config file, at least I found the following workaround:

I adapted the answer from here: ( I didn't like the colouring choices )

Display NLog trace in RichTextBox

private void SetupRichTextBoxLogger()
   {
      NLog.Windows.Forms.RichTextBoxTarget target = new NLog.Windows.Forms.RichTextBoxTarget();
      target.Name = "RichTextBox";
      target.Layout = "${longdate} ${level:uppercase=true} ${logger} ${message}";
      target.ControlName = nameof(this.RichTextBox1);
      target.FormName = nameof(NewForm);
      target.AutoScroll = true;
      target.MaxLines = 0;
      target.UseDefaultRowColoringRules = true;
      AsyncTargetWrapper asyncWrapper = new AsyncTargetWrapper();
      asyncWrapper.Name = "AsyncRichTextBox";
      asyncWrapper.WrappedTarget = target;

      SimpleConfigurator.ConfigureForTargetLogging( asyncWrapper, LogLevel.Trace );
   }

Can this be used to test entire Windows Forms in AppVeyor?

Can I use it to test entire forms and apis I made on appveyor?

https://github.com/Elskom/Els_kom_new/issues/89 is the issue where I would like to unit test everything to ensure that the entire UI works before deployment on the CI (test failure from any unhandled exception would make CI build fail). This is so I can filter out crashes from some bug elsewhere in the UI that mysteriously would stop working or just crash on end users. And would also be able to identify as to what made a particular feature just flat out stop working.

NullReferenceException in RichTextBoxTarget SendTheMessageToRichTextBox

NLog through Microsoft.Extensions.Logging to write to a log file and a RichTextBox on the main application form. (Package versions: NLog.Extensions.Logging 5.3.2/NLog.Windows.Forms 5.2.0)

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at NLog.Windows.Forms.RichTextBoxTarget.SendTheMessageToRichTextBox(String logMessage, RichTextBoxRowColoringRule rule, LogEventInfo logEvent)
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Span`1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at System.Delegate.DynamicInvoke(Object[] args)
   at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
   at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
   at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.TextBoxBase.WndProc(Message& m)
   at System.Windows.Forms.RichTextBox.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, WM msg, IntPtr wparam, IntPtr lparam)
   at Interop.User32.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.Interop.Mso.IMsoComponentManager.FPushMessageLoop(UIntPtr dwComponentID, msoloop uReason, Void* pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(msoloop reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(msoloop reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at MyLibrary.SingleInstance..ctor(Form mainForm, SingleInstanceTypes type) in C:\SandBox\Libraries\UI\Lear.UI\SingleInstance.cs:line 104
   at MyApp.Program.Main(String[] args) in C:\Sandbox\LPS3Services\Projects\MessageRouter\LPS.MessageRouter.Monitor\Program.cs:line 38

See also: https://stackoverflow.com/q/76789531/193178

Guessing BeginInvoke followed by CloseTarget doing detach will cause the NullReferenceException

Known issue: some tests are failing locally

See #14: we have

  • CustomRowColoringTest,
  • CustomWordRowColoringTest,
  • NoColoringTest
  • and SimpleRichTextBoxTargetTest
    working on AppVeyor, but failing locally (xunit 1,2; win 10 x64) because of font/font size tags.

Either this is because of some RTB control differences between windows versions, or because of some OS settings. It's also not clear how to properly fix the tests.

Anyway, while they are failing it's good to have the list here, so developers would not worry of broken tests.

InvalidOperationException when stopping application

2016-06-01 10:36:39.7052 Info Shutting down logging...
2016-06-01 10:36:39.7052 Info Stopping file watching for path 'E:\vsProject\MoNiQi\MoNiQi216\bin\Debug' filter 'NLog.config'
2016-06-01 10:36:39.7052 Info Closing old configuration.
2016-06-01 10:36:39.7832 Warn System.InvalidOperationException: 在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke。
   在 System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
   在 System.Windows.Forms.Control.BeginInvoke(Delegate method, Object[] args)
   在 System.Windows.Forms.Control.BeginInvoke(Delegate method)
   在 NLog.Windows.Forms.RichTextBoxTarget.DetachFromControl()
2016-06-01 10:36:39.7832 Error Error closing target 'RichTextBox Target[rtb]'. Exception: System.InvalidOperationException: 在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke。
   在 System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
   在 System.Windows.Forms.Control.BeginInvoke(Delegate method, Object[] args)
   在 System.Windows.Forms.Control.BeginInvoke(Delegate method)
   在 NLog.Windows.Forms.RichTextBoxTarget.DetachFromControl()
   在 NLog.Windows.Forms.RichTextBoxTarget.CloseTarget()
   在 NLog.Targets.Target.Close()
2016-06-01 10:36:39.7832 Warn Exception while closing. Exception: System.InvalidOperationException: 在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke。
   在 System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
   在 System.Windows.Forms.Control.BeginInvoke(Delegate method, Object[] args)
   在 System.Windows.Forms.Control.BeginInvoke(Delegate method)
   在 NLog.Windows.Forms.RichTextBoxTarget.DetachFromControl()
   在 NLog.Windows.Forms.RichTextBoxTarget.CloseTarget()
   在 NLog.Targets.Target.Close()
   在 NLog.Targets.Target.NLog.Internal.ISupportsInitialize.Close()
   在 NLog.Config.LoggingConfiguration.Close()

my code is only , when I close the form , above error display

public partial class Form_Main : Form
    {
        private ILogger log;
        public Form_Main()
        {
            InitializeComponent();
        }

        private void Form_Main_Load(object sender, EventArgs e)
        {
            log = LogManager.GetLogger("mnq");
        }
    }

Dynamic attachment to RichTextBoxes

There's an issue with RichTextBox target described in NLog/NLog#133 in 2012. The essence of the problem is that RichTextBox target attempts to attach to it's control at initialization, and if it can't find the control, it creates a separate form. This imposes very strict restriction of not accessing any NLog code before all referenced controls are created.

Other solution is to dynamically update logging configuration on creation/deletion of controls which requires writing a lot of boilerplate code, (see my response to NLog/NLog#133).

I've come with some compromise solution which I'd like to share. For our projects I've created another target totally based on RichTextBoxTarget code with the following modifications:

  • Removed everything related creation of custom form in case specified control is not found during InitializeTarget().
  • Allowed TargetRichTextBox property to be null if it's not found.
  • Added a check for TargetRichTextBox property not being null in the beginning of Write(...).
  • And added static RegisterTextBox()/UnregisterTextBox() so that it is possible to notify targets when controls appear/disappear.

The full code is here: https://gist.github.com/mikhail-barg/a9df4732868272cd9de5

This way the target could be specified in the NLog.config just as regular RichTextBox target, and only change in the application code would be to add registration/unregistration code for controls in proper places:

public Form1()
{
    InitializeComponent();
    RichTextBoxExtTarget.RegisterTextBox(this.richTextBoxLog);
    RichTextBoxExtTarget.RegisterTextBox(this.richTextBoxLogError);
}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
    RichTextBoxExtTarget.UnregisterTextBox(this.richTextBoxLog);
    RichTextBoxExtTarget.UnregisterTextBox(this.richTextBoxLogError);
}

This could probably be done automatically by creating a RichTextBox control descendant, but this looks like an overkill to me.

So, what do you think of my proposal? I've been using RichTextBoxTarget for 4 years now and never had any use for the auto-form creation, but on contrary - always had to juggle with initialization order to prevent it from appearing.

Crashes when logs an Error with exception

Hi

With RichTextBoxTarget the applicatin crashes when I try to log an Error with exception argument.

if (Logger.IsErrorEnabled)
                Logger.Error("This is a message", new Exception("simple exception"));

System.MissingMethodException

'Method not found: 'Void NLog.ILogger.Error(System.Exception, System.String)'.'

This is my 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">

  
  <targets>
      <target name="richTextBox" xsi:type="RichTextBox"
            layout="${time} : ${message}"
            formName="MainForm"
            ControlName="LogViewer"
            autoScroll="true"
            maxLines="20"
            useDefaultRowColoringRules="true"
            allowAccessoryFormCreation="false" />
  </targets>

  <rules>
    <logger name="*" minlevel="Info"  writeTo="richTextBox" />
  </rules>
</nlog>

RichTextBoxTarget: problem with logging stored messages during form creation

This happens if:

  • The target's MessageRetention strategy is set to something except None;
  • There's a Form with target's RTB that it shown after the target received some messages (i.e. there's something for it to log at form creation);
  • RichTextBoxTarget.ReInitializeAllTextboxes(this) is called from form's constructor.

This combination causes System.InvalidOperationException with message

Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
during the ReInitializeAllTextboxes call.

This is somewhat expected, because ReInitializeAllTextboxes causes target to call BeginInvoke on RTB control and in form's constructor it is not guaranteed to have a window handle yet.

The workaround would be to call RichTextBoxTarget.ReInitializeAllTextboxes(this) not form a form's constructor, but from it's Form.Load handler. But it's not obvious to user and also requires handling Load event even if you don't need it otherwise.

Create a nuget package with net5.0-windows platform supporting

The current nuget package has targets to .NET Framework 3.5 only. Is it possible to create and upload a nuget package with net5.0-windows target support?

It always has the ugly warning in visual studio:

Package 'NLog.Windows.Forms 4.4.0' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8' instead of the project target framework 'net5.0-windows7.0'. This package may not be fully compatible with your project.

Adding clickable links to RichTextBoxTarget

As you may have noticed, we are using RichTextBoxTarget quite extensively. It's very handy to keep track of all the actions visually. We also using the target to store information on exceptions happening during program execution. Still printing whole stacktrace (including inner exceptions) floods the control area, and is not that useful.

ex1

But not printing stacktrace is bad as well — it's often needed to identify the problem source. So I was thinking that it would be nice to display only short description (exception message) given that it's possible to show all the exception details on demand. I came with the following solution.

It's possible to create in-place links in the RichTextBox control, so I've patched RTB-target to create links after logging events that contain exceptions. Exception objects are stored in a dictionary inside the target.

ex2

Target also adds an LinkClicked handler to the control, and exposes it's own ExceptionLinkClicked event, having Exception object as parameter.

public Form1()
{
     InitializeComponent();
     RichTextBoxExceptionTarget.ReInitializeAllTextboxes(this);
     RichTextBoxExceptionTarget.GetTargetForControl(richTextBoxLog).ExceptionLinkClicked += Form1_ExceptionLinkClicked;
}

void Form1_ExceptionLinkClicked(object sender, Exception e)
{
    MessageBox.Show(e.ToString(), "Exception details", MessageBoxButtons.OK);
}

ex3

I'm actually very pleased with the results and I think that such functionality could be of use for others (it actually puzzles me that I haven't thought of this solution earlier). Still to be published it might need a complete re-vamp, like passing logEvent parameters to ExceptionLinkClicked handler. Or generalizing the ability to add links by allowing it for log events without exceptions somehow.

So I'm posting it here to get your opinion first. What do you think?

Target Invalid : RichTextBox

Hello,

I would like to connect to a RichTextBox.

That's what I installed:

<?xml version="1.0" encoding="utf-8"?>"utf-8"?
<packages>>>helmets
  <package id="NLog" version="4.5.6" targetFramework="net452" />>
  <package id="NLog.Schema" version="4.5.6" targetFramework="net452" />>"net452".
  <package id="NLog.Windows.Forms" version="4.2.3" targetFramework="net452" />>"net452".

Here is my NLog.config file :

<?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"
      throwExceptions="true"
      internalLogLevel="Warn" internalLogFile=".\nlog-internal.log" >




  <targets>
    <target xsi:type="RichTextBox"
          controlName="richTextBox1" formName="Form1" autoScroll="true" maxLines="250"
          allowAccessoryFormCreation="false"  messageRetention="OnlyMissed"
              />
    <target xsi:type="EventLog"/>
  </targets>

    


 <rules>
    <logger name="*" minlevel="Trace" writeTo="richTextBox1" />
  </rules>
</nlog>

=> Warning This is an invalid xsi:type'http://nlog-project.org/schemas/NLog.xsd:RichTextBox'.

I tried to execute some examples of codes found on this site. Code that works for other people but I got the same warning.

Please, help me!

FormControl not found when calling .NET app via Windows Shell

I have a C# .NET 4.6.2 desktop app that works great in a normal execution of the *.exe. I recently had the need to call the *.exe file inside Excel VBA via Shell and i notice that NLog was not able to recognize the FormControl returning the error "(...) target cannot be found".

This is my config:

  <targets>
      <target name="file" xsi:type="File" fileName="C:/logs/${shortdate}.log"  layout="${longdate} > ${logger}|${level}|${message}${exception:format=tostring}"/>
      <target name="control" xsi:type="FormControl" controlName="textBox1" formName="Form1" layout="${longdate}  >  ${message}${exception:format=tostring}" />
  </targets>
  <rules>
    <logger name="*" minlevel="Warn" writeTo="file" />
    <logger name="*" level="Info" writeTo="control" />
  </rules>

latest nlog (4.3) do not compatible

Error Error initializing target 'RichTextBox Target[rtb]'. Exception: NLog.NLogRuntimeException: NLog.Windows.Forms.RichTextBoxTarget.allLayouts is null. Call base.InitializeTarget() in NLog.Windows.Forms.RichTextBoxTarget
在 NLog.Targets.Target.Initialize(LoggingConfiguration configuration)

after I update to latest nlog it broken..

this is my config

<target xsi:type="RichTextBox"
        name="rtb" 
        layout="${date:format=MM-dd HH\:mm\:ss}|${uppercase:${level}}|${logger}|${message}"
        controlName="richTextBox1" 
        formName="Form1"
        useDefaultRowColoringRules ="true" maxLines="200" autoScroll="true"/>

No RowColor for RichTextBoxTarget when LeftToRight.Yes set

Nlog: 4.7.10
NLog.Windows.Forms: 4.4.0
Platform: net5.0-windows

Here is my code example based on this example:

            RichTextBox rtbLogs = new RichTextBox();
            rtbLogs.Dock = DockStyle.Fill;
            rtbLogs.Name = "rtbLogs";
            rtbLogs.ReadOnly = true;
            rtbLogs.BorderStyle = BorderStyle.FixedSingle;
            rtbLogs.BackColor = Color.White;

            this.Controls.Add(rtbLogs);

            RichTextBoxTarget target = new RichTextBoxTarget();
            target.Layout = "${longdate} [${threadname:whenEmpty=${threadid}}] ${uppercase:${level}} ${message:withException=true} ${all-event-properties}";
            target.TargetRichTextBox = rtbLogs;
            target.UseDefaultRowColoringRules = true;
            NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, NLog.LogLevel.Trace);

It hightlights the text fine:
image

But when I try to set RightToLeft = RightToLeft.Yes for main form after I initialized the RichTextBoxTarget then the hightlight is gone. And it shows just a regular text:
image

MessageBox: Error creating window handle

ERROR:
System.ComponentModel.Win32Exception non è stata gestita
ErrorCode=-2147467259
HResult=-2147467259
Message=Errore durante la creazione dell'handle della finestra.
NativeErrorCode=1406
Source=System.Windows.Forms

C# CODE:
var msgboxTarget = new MessageBoxTarget();
config.AddTarget("Msg", msgboxTarget);

        msgboxTarget.Layout = "${longdate} - ${uppercase:${level}} - ${logger} - ${message}";
        msgboxTarget.Caption = "Test";

        var msgboxRule = new LoggingRule("*", LogLevel.Fatal, msgboxTarget);
        config.LoggingRules.Add(msgboxRule);

        Logger Log = LogManager.GetCurrentClassLogger();
        Log.Fatal("Premuto Bottone Fatal");

ENVIRONMENT:
Visual Studio 2015 Community Edition
NET Framework 4.6.1
NLog v 4.3.7
NLog.Windows.Forms v 4.2.3

Form hanging when RichTextBox target nonstop logging

NLog version: (e.g. 4.6.8)

Platform: .Net 4.0

Current NLog config (xml or C#, if relevant)

<?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">

  <targets async="true">
    <target name="TraceTarget" xsi:type="File"
            layout="${level:uppercase=true:padding=-5} ${date:format=yyyy\-MM\-dd\ HH\:mm\:ss\.fff} - ${message}"
            fileName="${basedir}/Log/${date:yyyyMMdd}_Trace.txt"
            maxarchivefiles="1"
            />
  </targets>

  <rules>
    <logger ruleName="Trace" name="Trace" minlevel="Debug" writeTo="TraceTarget" />
  </rules>
</nlog>

code

 RichTextBoxTarget _target = new RichTextBoxTarget
            {
                Name = targetName,
                Layout = "[${level:uppercase=true:padding=-5}]" +
                          "${date:format=yyyy\\-MM\\-dd\\ HH\\:mm\\:ss\\.fff} " +
                          "${message} " +
                          "${exception:innerFormat=tostring:maxInnerExceptionLevel=10:separator=,:format=tostring}",
                ControlName = richTextBoxName,
                FormName = formName,
                AutoScroll = true,
                MaxLines = Convert.ToInt32(CommonFunction.ReadSetting("RichTextBoxMaxLines")),
                UseDefaultRowColoringRules = true,
                CreatedForm = false,
                AllowAccessoryFormCreation = false,
            };
  • What is the current result?
    I use RichTextBox target and when nonstop logging, the Form(WPF) will hanging (ex. i can't drag move the Form or i can't click any control on the Form), but the text of controls are working perfectly.
  • What is the expected result?
    I would expect when nonstop logging, UI controls can be working.
  • Did you checked the Internal log?
    Yes
  • Please post full exception details (message, stacktrace, inner exceptions)
    None
  • Are there any workarounds?
    No
  • Is there a version in which it did work?
    Don't think so
  • Can you help us by writing an unit test?
    Sorry, I don't know how to writing an unit test

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.