Giter Site home page Giter Site logo

nlog / nlog Goto Github PK

View Code? Open in Web Editor NEW
6.2K 277.0 1.4K 112.37 MB

NLog - Advanced and Structured Logging for Various .NET Platforms

Home Page: https://nlog-project.org

License: BSD 3-Clause "New" or "Revised" License

C# 99.90% PowerShell 0.10% Batchfile 0.01%
nlog logging logging-library netstandard netcore netstandard20 uwp structured-logging xamarin csharp

nlog's Introduction

NLog

NuGet Semantic Versioning NuGet downloads

Coverage

NLog is a free logging platform for .NET with rich log routing and management capabilities. It makes it easy to produce and manage high-quality logs for your application regardless of its size or complexity.

It can process diagnostic messages emitted from any .NET language, augment them with contextual information, format them according to your preference and send them to one or more targets such as file or database.

Major and minor releases will be posted on project news.

Getting started

For the possible options in the config, check the Options list and API Reference

Having troubles? Check the troubleshooting guide


ℹ️ NLog 5.0 Released!

NLog 5.0 is finally here. See List of major changes in NLog 5.0

NLog Packages

The NLog-nuget-package provides everything needed for doing file- and console-logging. But there are also multiple NLog extension packages, that provides additional target- and layout-output. See targets and layout renderers overview!

See Nuget/build status of all official packages here

Questions, bug reports or feature requests?

Issues with getting it working? Please check the troubleshooting guide before asking! With a clear error message, it's really easier to solve the issue!

Unclear how to configure NLog correctly of other questions? Please post questions on StackOverflow.

Do you have feature request or would you like to report a bug? Please post them on the issue list and follow these guidelines.

Frequently Asked Questions (FAQ)

See FAQ on the Wiki

Contributing

As the current NLog team is a small team, we cannot fix every bug or implement every feature on our own. So contributions are really appreciated!

If you like to start with a small task, then up-for-grabs are nice to start with.

Please note, we have a dev and master branch

  • master is for pure bug fixes and targets NLog 4.x
  • dev targets NLog 5

A good way to get started (flow)

  1. Fork the NLog repos.
  2. Create a new branch in you current repos from the 'dev' branch. (critical bugfixes from 'master')
  3. 'Check out' the code with Git or GitHub Desktop
  4. Check contributing.md
  5. Push commits and create a Pull Request (PR) to NLog

Please note: bugfixes should target the master branch, others the dev branch (NLog 5)

License

NLog is open source software, licensed under the terms of BSD license. See LICENSE.txt for details.

How to build

Use Visual Studio 2019 and open the solution 'NLog.sln'.

For building in the cloud we use:

  • AppVeyor for Windows- and Linux-builds
  • SonarQube for code coverage

Trying to build your fork in the cloud? Check this how-to

Note: master points to NLog 4.x and dev to NLog 5.x

nlog's People

Contributors

304notmodified avatar alexangas avatar andregleichner avatar awardle avatar bhaeussermann avatar brutaldev avatar c0shea avatar cvanbergen avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar eduardorascon avatar epignosisx avatar grbinho avatar ie-zero avatar ilya-g avatar inez avatar jamesuk189 avatar jkowalski avatar kevindaub avatar kichristensen avatar mikebairdrocks avatar nazim9214 avatar niklas-peter avatar parthdesai avatar repo-ranger[bot] avatar s-sreenath avatar snakefoot avatar stefandevo avatar vladikk 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  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  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  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  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  avatar  avatar  avatar

nlog's Issues

A bug in NLog.Internal.PropertyHelper? When using MethodCall target...

Reported in the forum at post: http://nlog-project.org/forum.html#nabble-tc1685644|a1685644

 

I'm using NLog with MethodCall target to save log events to database using my own method which is calling stored procedure. I don't want to use Database target as it gives me little control on how the stored procedure is called, and what if that call fails. I discovered that 'type' attribute of MethodCall parameters is ignored (I'm using version 1.0.0.505). This is annoying, because default type is System.String, so I'd have to change all arguments of my method to String, otherwise convert exception is thrown. Why 'type' attribute is ignored? A quick code search lead me to NLog.Internal.PropertyHelper.AddArrayItemFromElement method, where there is a call to another method - ConfigureObjectFromAttributes. ConfigureObjectFromAttributes takes 4 arguments, last one being bool - ignoreType is his name. It turned out that when it is set to false it ignores 'type' attributes. So, this is the root of the problem.

 

My question is - why is ignoring type attribute there (Internal/PropertyHelper.cs, line 154) turned on? Is this intentional?

 

cheers

potential bug with static logger

Reported in the forum at post: http://nlog-project.org/forum.html#nabble-tc1685649|a1685649

 

I have a rather bizarre scenario where a logger defined as static (per the performance recommendations) will only log one time. The application is an NT service, which executes functions from the threadpool on arbitrary assemblies. So, the call stack looks like:

 

QueueUserWorkItem to ThreadPool

static ThreadProc

Invoke method dynamically on assembly (Activator.CreateInstance, Invoke)

 

Within the Invoked function is where the logger is declared. It works fine if instantiated each call, but not if declared as static. I am using async logging targets as well.

BUG: targets async="true" ignored identity impersonate

Reported in the forum at post: http://nlog-project.org/forum.html#nabble-tc1685903|a1685903

 

If you are running with <identity impersonate="true"...> in your web.config and you set targets async="true", the lazy writer thread doesn't work under the context of your impersonated identity. If you instead put in a AsyncWrapper, that works fine. If you use async="true" and put in an ImpersonatingWrapper duplicating the info in your identity impersonate in web.config that works fine (but is of course undesirable).

Moved from http://nlog.codeplex.com/workitem/2717

Comments:
Scratch that, my config change wasn't picked up for some reason. Even the AsyncWrapper doesn't impersonate without having an impersonatingwrapper.

Also I'm finding that if I try to load the page again while the lazy writer is still retrying (I have a retrying wrapper inside the asyncwrapper), it waits for the batch to finish before letting me in. Maybe this is required for thread safety or something but it makes the async not so much async...

I can tell the lazy writer is in the middle of writer from the debugging log when I put nlog in debug mode and because I see the following in my debug window:

A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll
A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll
A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll
A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll
A first chance exception of type 'System.UnauthorizedAccessException' occurred in NLog.DLL

and in my debug log:

2008-04-11 17:00:00.2757 Warn Error while writing to 'f3:FileTarget': System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode)
at NLog.Internal.FileAppenders.BaseFileAppender.WindowsCreateFile(String fileName, Boolean allowConcurrentWrite)
at NLog.Internal.FileAppenders.BaseFileAppender.TryCreateFileStream(Boolean allowConcurrentWrite)
at NLog.Internal.FileAppenders.BaseFileAppender.CreateFileStream(Boolean allowConcurrentWrite)
at NLog.Internal.FileAppenders.RetryingMultiProcessFileAppender.Write(Byte[] bytes)
at NLog.Targets.FileTarget.WriteToFile(String fileName, Byte[] bytes, Boolean justData)
at NLog.Targets.FileTarget.Write(LogEventInfo logEvent)
at NLog.Targets.Wrappers.RetryingTargetWrapper.Write(LogEventInfo logEvent)
2008-04-11 17:00:00.7767 Warn Retry #1
2008-04-11 17:00:00.7917 Warn Error while writing to 'f3:FileTarget': System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode)
at NLog.Internal.FileAppenders.BaseFileAppender.WindowsCreateFile(String fileName, Boolean allowConcurrentWrite)
at NLog.Internal.FileAppenders.BaseFileAppender.TryCreateFileStream(Boolean allowConcurrentWrite)
at NLog.Internal.FileAppenders.BaseFileAppender.CreateFileStream(Boolean allowConcurrentWrite)
at NLog.Internal.FileAppenders.RetryingMultiProcessFileAppender.Write(Byte[] bytes)
at NLog.Targets.FileTarget.WriteToFile(String fileName, Byte[] bytes, Boolean justData)
at NLog.Targets.FileTarget.Write(LogEventInfo logEvent)
at NLog.Targets.Wrappers.RetryingTargetWrapper.Write(LogEventInfo logEvent)
2008-04-11 17:00:01.2927 Warn Retry #2
2008-04-11 17:00:01.3077 Warn Error while writing to 'f3:FileTarget': System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode)
at NLog.Internal.FileAppenders.BaseFileAppender.WindowsCreateFile(String fileName, Boolean allowConcurrentWrite)
at NLog.Internal.FileAppenders.BaseFileAppender.TryCreateFileStream(Boolean allowConcurrentWrite)
at NLog.Internal.FileAppenders.BaseFileAppender.CreateFileStream(Boolean allowConcurrentWrite)
at NLog.Internal.FileAppenders.RetryingMultiProcessFileAppender.Write(Byte[] bytes)
at NLog.Targets.FileTarget.WriteToFile(String fileName, Byte[] bytes, Boolean justData)
at NLog.Targets.FileTarget.Write(LogEventInfo logEvent)
at NLog.Targets.Wrappers.RetryingTargetWrapper.Write(LogEventInfo logEvent)
2008-04-11 17:00:01.8087 Warn Retry #3
2008-04-11 17:00:01.8197 Warn Error while writing to 'f3:FileTarget': System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode)
at NLog.Internal.FileAppenders.BaseFileAppender.WindowsCreateFile(String fileName, Boolean allowConcurrentWrite)
at NLog.Internal.FileAppenders.BaseFileAppender.TryCreateFileStream(Boolean allowConcurrentWrite)
at NLog.Internal.FileAppenders.BaseFileAppender.CreateFileStream(Boolean allowConcurrentWrite)
at NLog.Internal.FileAppenders.RetryingMultiProcessFileAppender.Write(Byte[] bytes)
at NLog.Targets.FileTarget.WriteToFile(String fileName, Byte[] bytes, Boolean justData)
at NLog.Targets.FileTarget.Write(LogEventInfo logEvent)
at NLog.Targets.Wrappers.RetryingTargetWrapper.Write(LogEventInfo logEvent)
2008-04-11 17:00:02.3197 Warn Retry #4
2008-04-11 17:00:02.3347 Warn Error while writing to 'f3:FileTarget': System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode)
at NLog.Internal.FileAppenders.BaseFileAppender.WindowsCreateFile(String fileName, Boolean allowConcurrentWrite)
at NLog.Internal.FileAppenders.BaseFileAppender.TryCreateFileStream(Boolean allowConcurrentWrite)
at NLog.Internal.FileAppenders.BaseFileAppender.CreateFileStream(Boolean allowConcurrentWrite)
at NLog.Internal.FileAppenders.RetryingMultiProcessFileAppender.Write(Byte[] bytes)
at NLog.Targets.FileTarget.WriteToFile(String fileName, Byte[] bytes, Boolean justData)
at NLog.Targets.FileTarget.Write(LogEventInfo logEvent)
at NLog.Targets.Wrappers.RetryingTargetWrapper.Write(LogEventInfo logEvent)
2008-04-11 17:00:02.3347 Error Error in lazy writer timer procedure: System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at NLog.Targets.Wrappers.RetryingTargetWrapper.Write(LogEventInfo logEvent)
at NLog.Target.Write(LogEventInfo[] logEvents)
at NLog.Targets.Wrappers.AsyncTargetWrapper.LazyWriterTimerCallback(Object state)

If I move the retrywrapper outside the asyncwrapper it doesn't retry at all.

If I take out the retrywrapper I only got this message while the lazy writer is working and because I don't have a delay on retry it's hard to tell if it's making me wait or not. Seems like not if I had to guess.

A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll

2008-04-11 16:48:24.9957 Error Error in lazy writer timer procedure: System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode)
at NLog.Internal.FileAppenders.BaseFileAppender.WindowsCreateFile(String fileName, Boolean allowConcurrentWrite)
at NLog.Internal.FileAppenders.BaseFileAppender.TryCreateFileStream(Boolean allowConcurrentWrite)
at NLog.Internal.FileAppenders.BaseFileAppender.CreateFileStream(Boolean allowConcurrentWrite)
at NLog.Internal.FileAppenders.RetryingMultiProcessFileAppender.Write(Byte[] bytes)
at NLog.Targets.FileTarget.WriteToFile(String fileName, Byte[] bytes, Boolean justData)
at NLog.Targets.FileTarget.Write(LogEventInfo[] logEvents)
at NLog.Targets.Wrappers.AsyncTargetWrapper.LazyWriterTimerCallback(Object state)

I don't see any exceptions from NLog.dll in this case. I wonder if there's also a problem with the retry in an async.

I'm working in ASP.NET 3.5 in VS2008.

This is a snippet of my config:

Trouble with logger.name not equal to "*"

I am using NLog 1.0.0.505 (compiled from source without modification) from a .Net application.

 

If under rules.logger I have

logger name="*" minlevel="Info" writeto="progress"

and under targets.target name="progress" xsi:type="File" layout="${callsite}" ...

my log file shows

LogInfo.Log.LogActivity

as the Namespace.Class.Method information.

 

However, if I substitute "LogInfo.Log" or "LogInfo.*" for "*" in logger name,

I don't get any logging to the "progress" log file, and I see:

Debug Targets for NLog by level

Debug Trace =>

Debug Debug =>

Debug Info =>

Debug Warn =>

Debug Error =>

Debug Fatal =>

in the NLog internal log output.

 

I don't know if this is a bug or a shortage in my understanding

Comments:
I find that NLog.LogFactory.GetTargetsByLevelForLogger, when called from NLog.LogFactory.GetConfigurationForLogger, compares the name for the logger ("NLog" in my case) to the value of the name attribute of the rule ("LogInfo.Log" in my case), finds that it doesn't get an exact match, and does not add the target to the list of targets for level.

This does not seem to be the behavior suggested by the examples under the Rules section under
http://nlog-project.org/config.html#file
in the documentation.

The Rules section does say that the name attribute is the source/logger name.
I'm trying to use it for the source name, but it seems only to be accepting the logger name.

GetCurrentClassLogger() - frame.GetMethod().DeclaringType is null

Component: NLog
Impact: High
Release: NLog 2.0

In my application I get an error when I'm trying to create a logger.

my app-code:

public static class Start
{
    [STAThread]
    public static void Main(string[] args)
    {
     ...
     var logger = CommonLogManager.LogInstance.GetCurrentClassLogger();
     ...
    }
}

public static class CommonLogManager
{
    private const string CONFIG_FILE = &quot;NLog.config&quot;;
    private const string BIN_DIR = &quot;bin&quot;;

    public static readonly LogFactory LogInstance = new LogFactory(new XmlLoggingConfiguration(getNLogConfigFilePath()));

    private static string getNLogConfigFilePath()
    {
     try
     {
     var pathToExcecutable = Path.GetDirectoryName(Application.ExecutablePath);
     if (!String.IsNullOrEmpty(pathToExcecutable))
     {
     var config = Path.Combine(pathToExcecutable, CONFIG_FILE);
     if (!File.Exists(config))
     {
     var path = Path.Combine(pathToExcecutable, BIN_DIR);
     config = Path.Combine(path, CONFIG_FILE);

     if (!File.Exists(config))
     throw new FileNotFoundException(&quot;Die Konfigurationsdatei f&#252;r den Logger wurde nicht gefunden.&quot;, config);
 }
     return config;
     }

     throw new Exception(&quot;Der Pfad der Anwendung konnte nicht ermittelt werden.&quot;);
     }
     catch (Exception ex)
     {
     throw new Exception(&quot;Fehler im Logger&quot;, ex);
     }
 }
}

my modified NLog-code (in NLog.LogFactory | netfx35):

[MethodImpl(MethodImplOptions.NoInlining)]
public Logger GetCurrentClassLogger()
{
#if SILVERLIGHT
 var frame = new StackFrame(1);
#else
 var frame = new StackFrame(1, false);
#endif
 if (frame == null)
     throw new NullReferenceException(&quot;frame is null&quot;);

    if (frame.GetMethod() == null)
     throw new NullReferenceException(&quot;frame.GetMethod() is null&quot;);

    if (frame.GetMethod().DeclaringType == null)
 throw new NullReferenceException(frame.GetMethod().Name + &quot; frame.GetMethod().DeclaringType is null&quot;);

 if (frame.GetMethod().DeclaringType.FullName == null)
 throw new NullReferenceException(&quot;frame.GetMethod().DeclaringType.FullName is null&quot;);

 return this.GetLogger(frame.GetMethod().DeclaringType.FullName);
}

Moved from http://nlog.codeplex.com/workitem/6999

CookieContainer for WebServiceTarget can not be set

I am using webService target for auditing users from my winform applications, which is based on massive webService communication with my central server. At first, they login through a webService and if successfull, then create Authentication cookie through FormsAuthentication.SetAuthCookie(userName, false); This is stored in my application in CookieContainer variable, so every next webService request is done in the same authorized user context and I can get the user in webservice.

What I need is to pass the CookieContainer used by my application to NLog webService "engine" calling my Audit web method, so inside of that, I can get the user for which I am writing the audit.

This is very easily solvable by publishing new private CookieContainer _cookieContainer property in NLog-1.0-Refresh\src\NLog\Targets\WebService.cs file, and then assigning to the HttpWebRequest.CookieContainer property in InvokeSoap11() method as I have done for my self. For more details please see attached edited file.

Handle Leak with none existent TCP Receiver

Hi,

 

There seems to be a handle/memory leak occurring when you have a non-existent TCP target in your NLog.Config.

 

We usually use UDP logging with Log2Console displaying the messages but I had forgotten that i had added a tcp4 receiver for test purposes into the NLog.Config file. Unfortunately there wasn't the respective receiver created in Log2Console. When debugging my app i found that the number of GC Handles and memory was continuously increasing as i am writing data at quite high speed to the logger. After further tests i found that it was being generated by the NLog dll (version 2 dll). To test this i created a simple app that wrote to the logger every 10ms. Doing that really shows the memory and handles increasing. If i then removed the tcp4 target the memory and handles stay pretty much the same however long you let it run for.

 

regards,

 

Simon

Moved from http://nlog.codeplex.com/workitem/6142

minLevel in 2.0 beta

I had an issue, or potentially expectation confusion when setting up the configuration for the logger. I used the tutorial example setting the minLevel=”Info”. The tutorial says that all levels with “Info” or higher should be emitted. However, after playing with the tool for some time, I discovered that the minLevel does not seem to do much. Using[ levels="Trace,Debug,Info,Warn,Error,Fatal"] resulted in expected results. Perhaps this is a change in 2.0?

When setting a minLevel=”Info” all that was emitted was Info events. This is the behavior I would expect for the “Level” attribute. I was expecting that all events > minLevel would be emitted.

 

<targets>

<target name="logfile" xsi:type="File" fileName="file.txt" />

</targets>

<rules>

<logger name="*" minlevel="Info" writeTo="logfile" />

</rules>

Moved from http://nlog.codeplex.com/workitem/6085

Can't get anything in NLogViewer on Vista 2 lines of code to fix

Included becuse it showed up several times and might be easier to fix than ignore.

Reported in the forum at post: http://nlog-project.org/forum.html#nabble-td2158677|a2158677

The solution is to change 2 lines in UDPReceiver.cs

using (Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp))
{
    socket.Bind(new IPEndPoint(IPAddress.IPv6Any, this.Port));
    IPEndPoint sender = new IPEndPoint(IPAddress.IPv6Any, 0);

Treat environment variable value as Layout

In order to generically assign a log directory for various environments, eg development, production (server) etc I had a need for the following:

1. set environment variable NLOG_BASE=D:\CommonLogs\${processname}\Logs

2. In NLog.config: create

<variable name="logdir" value="${whenEmpty:whenEmpty=${basedir:dir=Logs}:inner=${environment:NLOG_BASE}}"/>

3. In the target(s): fileName="${logdir}/debug.${shortdate}.txt"

However the environment renderer does not process the environment variable value as a Layout.

I have modified the EnvironmentLayoutRenderer code and attached it here.

This is a non-breaking change, and I recommended it be included in the next release.

Moved from http://nlog.codeplex.com/workitem/6873, were attached file also can be found

Enable Serialization of current LoggingConfiguration

After programmatically adding targets, rules, etc. it would be nice to be able to serialize the result to XML. I may have missed it but attempting to use XmlSerializer gives an error due to no parameter-less constructor. I am assuming that such code exists somewhere in NLog but is not exposed. I am using the latest NLog 2.0 due to my need for the ReplaceLayoutRendererWrapper.

IPV6-Bug

Reported in the forum at post: http://nlog-project.org/forum.html#nabble-tc1685313|a1685313

Hi!

I got an error while trying to log to chainsaw or nlog-viewer; I have some IPV6-stuff on my system, that apparently confuses the NLog.Internal.NetworkSenders.TcpNetworkSender:

When connectiong to localhost, the Dns.GetHostEntry-AddressList has on index 0 an wired entry (::1) that can't be used to connect to the network-logger.

I atteched a patch that was manly inspired by http://odalet.wordpress.com/2007/01/

This patch solves the problem and should not conflict with other network-configurations...

Tschö, Ruben

Add a Unique ID per log event visible by a Layout Renderer

When logging to various targets there isn't a specific way (that I"m aware of) to link the log events together. The ${guid} layout renderer generates a unique id for each layout. So could we get a single unique reference id that all targets could expose?

 

I'd be happy to look into an implementation of this and provide a patch if needed.

CodePlex bug 2599 - TraceTarget blocks application when logging error events - Trace.Fail

My application - a windows service - stops working when logging errors to TraceTarget.
The Write method in TraceTarget calls Trace.Fail which causes the application to stop an and popup a retry/abort/ignore dialog.

Trace.cs
if (logEvent.Level >= LogLevel.Error)
{
Trace.Fail(CompiledLayout.GetFormattedMessage(logEvent));
}
else
{
Trace.WriteLine(CompiledLayout.GetFormattedMessage(logEvent));
}

BufferingWrapper over compound target doesn't work

Reported in the forum at post: http://nlog-project.org/forum.html#nabble-td3270376|a3270376

I'm not sure was it intended to work in the initial design but doesn't in the following config file.
Buffering only works when declared over each target. But if network share becomes unreachable then all the buffer data will be lost and FallbackTarget switches to the next one.

<?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" internalLogFile="C:\Temp\nlog.log" throwExceptions="true" internalLogLevel="Trace">

 <variable name="FCUCopyResultLogPath" value="${gdc:FCUCopyResultLogPath}"/>
 <variable name ="FCUCopyResultLogName" value="${gdc:FCUCopyResultLogName}"/>
 <variable name="SizeThreshold" value="524288"/>
 <variable name ="MaxArchiveFiles" value="1000"/>

 <targets async="false">
 <wrapper-target xsi:type="BufferingWrapper" bufferSize="1000" name="testBuffer">
 <compound-target xsi:type="FallbackGroup" name="FallbackGroup" returnToFirstOnSuccess="false">
 <target name="primaryFile"
 xsi:type="File"
 fileName="${FCUCopyResultLogPath}"
 networkWrites="true"
 concurrentWrites="false"
 encoding="utf-16"
 archiveAboveSize="${SizeThreshold}"
 deleteOldFileOnStartup="true"
 maxArchiveFiles="${MaxArchiveFiles}">

 <layout xsi:type="CSVLayout" delimiter="Tab">
 <column name="time" layout="${longdate}" />
 <column name="message" layout="${message}" />
 <column name="logger" layout="${logger}"/>
 <column name="level" layout="${level}"/>
 </layout>
 </target>
 <target name="secureFile"
 xsi:type="File"
 fileName="${specialfolder:folder=DesktopDirectory:upperCase=true}\${FCUCopyResultLogName}"
 networkWrites="false"
 concurrentWrites="false"
 encoding="utf-16"
 archiveAboveSize="${SizeThreshold}"
 deleteOldFileOnStartup="true"
 maxArchiveFiles="${MaxArchiveFiles}">

 <layout xsi:type="CSVLayout" delimiter="Tab">
 <column name="time" layout="${longdate}" />
 <column name="message" layout="${message}" />
 <column name="logger" layout="${logger}"/>
 <column name="level" layout="${level}"/>
 </layout>
 </target>
 </compound-target>
 </wrapper-target>
 </targets>

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

UTF8 should write BOM (optional) (FileTarget)

When you add encoding="utf-8" on a file target, encoding of the result file is a UTF-8 encoding but the preamble (Binary Object Mark) is not present at the start of the file then some tools that use this BOM not recognize the encoding as UTF-8...

In https://github.com/jkowalski/NLog/blob/master/src/NLog/Targets/FileTarget.cs source file

I suggest to add preamble bytes as below:

Method "WriteToFile", line 964

 private void WriteToFile(string fileName, byte[] bytes, bool justData)
 {
     if (this.ReplaceFileContentsOnEachWrite)
     {
         using (FileStream fs = File.Create(fileName))
         {
             //get preamble bytes
             byte[] preambleBytes = this.Encoding.GetPreamble();
             byte[] headerBytes = this.GetHeaderBytes();
             byte[] footerBytes = this.GetFooterBytes();
             //write preamble bytes
             if (preambleBytes != null)
             {
                 fs.Write(preambleBytes, 0, preambleBytes.Length);
             }
             if (headerBytes != null)
             {
                 fs.Write(headerBytes, 0, headerBytes.Length);
             }
             fs.Write(bytes, 0, bytes.Length);
             if (footerBytes != null)
             {
                 fs.Write(footerBytes, 0, footerBytes.Length);
             }
         }
         return;
     }

     /* some source code ... */
     if (writeHeader && !justData)
     {
         //get preamble bytes
         byte[] preambleBytes = this.Encoding.GetPreamble();
         //write preamble bytes
         if (preambleBytes != null)
         {
             appenderToWrite.Write(preambleBytes);
         }
         byte[] headerBytes = this.GetHeaderBytes();
         if (headerBytes != null)
         {
             appenderToWrite.Write(headerBytes);
         }
     }
     /* end of method */
 }

Moved from http://nlog.codeplex.com/workitem/6831

Logging takes forever when archiving has hit maxint counter

Imported from SF.NET (2847706) https://sourceforge.net/tracker/?func=detail&aid=2847706&group_id=116456&atid=675007

 

When archiving has been enabled and archiving to files with a counter and

counter has reached maxint,

then logging takes very looooong to complete and nothing is archived

anymore.

 

My log and archive settings for file target are:

<target name="filelog" xsi:type="AutoFlushWrapper">

<target xsi:type="File"

FileName="${basedir}/logs/YourApplicationName.txt"

Layout="${longdate}|${level:uppercase=true}|(${logger}) ${message}

${exception:format=message}"

ArchiveFileName="${basedir}/logs/archives/YourApplicationName.{##}.txt"

ArchiveAboveSize="64"

ArchiveNumbering="FileTarget.ArchiveNumberingMode.Sequence"

MaxArchiveFiles="3"

ConcurrentWrites="false" />

</target>

 

Size set to 64 bytes for testing purposes.

Moved from http://nlog.codeplex.com/workitem/2318

AutoReload not working on Windows CE

Reported in the forum at post: http://nlog-project.org/forum.html#nabble-tc1685628|a1685628

 

Hi all

 

I am using NLog 1.0 CE build in Windows CE 5 and .NET CF 2.0. I am trying to get the autoReload function to work so that logging can be configured on the fly but without any success. I have watched the logger objects in code and it is pointing at the correct file etc, but when I paste a new file configuration over the current configuration, no changes happen (watched the ConfigurationChanged event in code and it also doesn't trigger).

 

This is my configuration file:

 

<?xml version="1.0" ?>

<nlog autoReload="true" xmlns="http://www.nlog-project.org/schemas/NLog.xsd"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<targets>

<target name="file" xsi:type="File"

layout="${callsite} ${longdate} ${message} ${exception:format=tostring}"

fileName="${basedir}/logs/logfile.txt"

archiveFileName="${basedir}/logs/archives/log.{#####}.txt"

archiveAboveSize="512"

archiveEvery="Day"

archiveNumbering="Sequence"

concurrentWrites="true"

keepFileOpen="false"

maxArchiveFiles="7"

encoding="iso-8859-2" />

<target name="console" xsi:type="Console" layout="${date:format=HH\:MM\:ss} ${logger} ${message}" />

<target name="n" xsi:type="Null" layout="${message}" formatMessage="true" />

</targets>

<rules>

<logger name="*" minlevel="Trace" writeTo="n" />

</rules>

</nlog>

 

In code, I have a number of classes that each use a different non-static logger reference - I have also tried to make these the same reference but no change.

 

Any ideas, or am I just doing something stupid?

 

Thanks

Moved from http://nlog.codeplex.com/workitem/2702

Comments:
Your configuration file is correctly, but there is 2 configuration files in your project. As you know , in the website "http://nlog-project.org/wiki/Visual_Studio_support", it's said that"you need to change 'Copy To Output Directory' option on the NLog.config to 'Copy Always' ", so, , we're only need to set the copyed configuration files.If you do this , it can work.

.net default app config file name change

Reported in the forum at post: http://nlog-project.org/forum.html#nabble-tc1685988|a1685988

 

Hi,

 

When we upgraded to visual studio 2008, the default application configuration file name changed from app.exe.config to app.config. The change only manifests when the application either doesn't use the configuration file at all or creates it dynamically by calling ConfigurationManager.OpenExeConfiguration.

 

Nevertheless, when NLog's LogFactory.Configuration getter calls AppDomain.CurrentDomain.SetupInformation.ConfigurationFile, it returns app.config instead of app.exe.config.

 

Since our existing .nlog files are named app.exe.nlog, they are no longer found by NLog.

 

Has anyone else encountered this problem?

 

If so, here is some code I added that makes NLog more flexible. Regardless of whether the config file is named app.exe.config or app.config, NLog will find a .nlog file named either app.nlog or app.exe.nlog.

 

excluded code of fix as requested

BufferedWrapper flush under async wrapper

Imported from SF.NET (1867821) https://sourceforge.net/tracker/?func=detail&aid=1867821&group_id=116456&atid=675007

 

The following configuration:

 

<targets async="True">

<target name="Mail" xsi:type="BufferingWrapper" bufferSize="2">

<target name="Mail" xsi:type="Mail" smtpServer="${smtpServer}"

from="[email protected]" to="${emails}" body="[${date}:

${logger}]${newline}${message}${fullexception}"

subject="${projectName} FATAL errors" addNewLines="True"/>

</target>

</targets>

 

Will loose logging events on appdomain unload.

 

it seems it's due to the fact, that flushing AsyncTargetWrapper does not

cause to Flush wrapped target.

 

So when LogManager.Flush() is called, async wrappers are flushed, but

buffered - are not.

Moved from http://nlog.codeplex.com/workitem/2320

Add an Enabled attribute to the logger rules

I'd like a quick way to enable/disable specific loggers. Yes, I can comment them out but I'd prefer an additional attribute that tells NLog whether the logger should be active. See the example below.

<rules>
<logger name="*" minlevel="Error" writeTo="console" enabled="true"/>
<logger name="MyProblemNameSpace.*" minlevel="Trace" writeTo="f1" enabled="false" />
</rules>

Moved from Codeplex http://nlog.codeplex.com/workitem/5138

Exceptions thrown when logging from C++/CLI

Imported from SF.NET (2849287): https://sourceforge.net/tracker/?func=detail&aid=2849287&group_id=116456&atid=675007

 

Exceptions get thrown from within StackTrace.cs while attempting to log a message sent from managed C++ code. It seems that the metadata for the stackframe information cannot be read properly. See attached screenshot.

 

One fix is to test contained objects for null before trying to access them.

Moved from http://nlog.codeplex.com/workitem/2317

Small bug in RichTextBoxTarget

Reported in the forum at post: http://nlog-project.org/forum.html#nabble-tc1685338|a1685338

 

Hello,

 

First off, THANKS for such a great logging framework. NLog is awesome :)

 

That being said, I just found a small bug in the RichTextBoxTarget.

 

In my project, I have a custom control (LogRichTextBox) that is a subclass of the RichTextBox control. When I try to use the RichTextBoxTarget, no text is output to the LogRichTextBox. However, if I change my code to use the standard RichTextBox instead of my custom control, then everything works great.

 

I've traced the problem down to FormHelper.FindControl(), which is used by the RichTextBoxTarget --

...

searchControl.GetType() == controlType

 

The method is searching for an _exact_ match between the control and RichTextBox, when it should be looking to see if searchControl can be cast to the controlType. i.e. searchControl.GetType().IsAssignableFrom(controlType).

 

Hope that helps :)

-Matt

The same NLog binary on Windows and Linux

We are building binaries on Windows only, but most of our console tools works fine on Linux under mono.

The only problem is NLog - if there is file target in config - everything (including logging) works fine until exit where all utilities hanging.

Utilities are merged into single .exe via ILMerge, so I cannot just replace NLog binary.

Is there a way to use NLog Windows binary on Linux?

Moved from http://nlog.codeplex.com/workitem/6291

Add ability to change Logger name at runtime

Currently we utilize a base interface that we can use through IOC to switch out the logger at runtime. Because of this, we don't always know what the actual log provider will be until runtime. It would be nice if we could pass in the Logger name through the interface and have that used instead of being set through LogManager.GetLogger( "name" ) or LogManager.GetCurrentClassLogger().

NLog.Targets.LogReceiverWebServiceTarget needs custom binding

receiveService.EndpointConfigurationName assumes that we have a clientconfig in our solution.

However, in SilverLight and PRISm, the config is not locally to our project within a solution. It is xap(ed) and having a basicHttpBinding section in the shell.xaml project, is really not a good solution.

So, I suggest that the LogReceiverWebServiceTarget supports a new method of type Binding so, we can create custom binding in code!

Moved from http://nlog.codeplex.com/workitem/6509

RichTextBoxTarget MaxLines property seems to be ignored

I've set it to be 400 lines, but the RichTextBox never seems to get cleared out.

With high volume logging this may cause the program to run out of memory.

Moved from http://nlog.codeplex.com/workitem/5506

Comments:
Looking at the source code, there is an error in the way NLog removes the top line in RichTextBoxTarget.SendTheMessageToRichTextBox:

if (this.MaxLines > 0)
{
this.lineCount++;
if (this.lineCount > this.MaxLines)
{
int pos = rtbx.GetFirstCharIndexFromLine(1);
rtbx.Select(0, pos);
rtbx.SelectedText = string.Empty;
this.lineCount--;
}
}

Setting the SelectedText property to string.Empty doesn't remove the lines. I added a TextChanged event to my rich text box and remove the top numLinesToRemove as follows (adapted from http://stackoverflow.com/a/9802296/1030471):

int pos = richTextBox.GetFirstCharIndexFromLine(numLinesToRemove);
richTextBox.Select(0, pos);
richTextBox.SelectedRtf = "{\rtf1\ansi\ansicpg1252\deff0\deflang1053\uc1 }";

Keep in mind that changing the SelectedRtf property will fire the TextChanged event, so you'll need to adjust the counter keeping track of the number of lines in your rich text box before you change the SelectedRtf property. I would recommend against using the Lines property as this has to parse through all the text and can get very slow (see http://stackoverflow.com/q/1136825/1030471).

Perhaps this could be fixed in the next NLog build.

NLogEvent does not contain Exception object

When translating from a LogEventInfo item to an NLogEvent item, any exception object stored in the LogEventInfo object is ignored and not transferred to the server.

Moved from http://nlog.codeplex.com/workitem/6725

Comments:
Yes I can confirm this. The only solution I've found is to convert the exception to a string (exception.ToString()) and use that as the log message, rather than passing the exception. Please fix.

target File maxArchiveFiles has no infinit value

The maxArchiveFiles attribute has no infinit value.

Proposal: Use for it the 0 like others!

 

I have my own system for manage log files amount and maxArchiveFiles useless in my case.

And it default value is awful.

 

"maxArchiveFiles - Maximum number of archive files that should be kept.Integer Default: 9"

http://nlog-project.org/wiki/File_target

 

Tested on NLog 2.0.

Moved from http://nlog.codeplex.com/workitem/6811

Unable to add log events from an external source

When invoking external tools that generate log information, it is difficult to get the complete set of information back into the targets due to the restrictive nature of the logger class. We have a case where we return from an external unmanaged process with a batch of messages with their own logger name, description, timestamp, and even optional stacktrace for errors. However this batched log information is impossible to feed back to the nlog framework since the logger class does not provide an API to do so.

Concurrent Access in File Target fails

Reported in the forum at post: http://nlog-project.org/forum.html#nabble-tc1685753|a1685753

 

I am attempting to use NLog in a multiple app domain process.

 

The log file has the following target

 

----------------------------------------------

<target name="DefaultLogFile"

 

concurrentWriteAttemptDelay="1"

concurrentWrites="true"

concurrentWriteAttempts = "10"

 

keepFileOpen="false"

autoFlush="false"

 

deleteOldFileOnStartup="true"

 

xsi:type="File"

layout="${level:uppercase=true} ${message}"

fileName="${basedir}/Log.log"

/>

-----------------------------------------------

 

The nlog internal trace file produces the following exception.

 

-----------------------------------------------

2008-06-02 11:34:05.7497 Error Target exception: System.IO.FileLoadException: The process cannot access the file because it is being used by another process. (Exception from HRESULT: 0x80070020)

at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)

at NLog.Internal.FileAppenders.BaseFileAppender.WindowsCreateFile(String fileName, Boolean allowConcurrentWrite)

at NLog.Internal.FileAppenders.BaseFileAppender.TryCreateFileStream(Boolean allowConcurrentWrite)

at NLog.Internal.FileAppenders.BaseFileAppender.CreateFileStream(Boolean allowConcurrentWrite)

at NLog.Internal.FileAppenders.RetryingMultiProcessFileAppender.Write(Byte[] bytes)

at NLog.Targets.FileTarget.WriteToFile(String fileName, Byte[] bytes, Boolean justData)

at NLog.Targets.FileTarget.Write(LogEventInfo logEvent)

at NLog.LoggerImpl.Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)

----------------------------------------------------------

 

The following line in RetryingMultiProcessFileAppender.Write(byte[] bytes) is suspect

 

using (FileStream fileStream = CreateFileStream(false))

 

If the above value is true rather than false then no exceptions occur in the internal trace file.

 

The false value means that in the BaseFileAppender.WindowsCreateFile() method it will end up opening the file without the FILE_SHARE_WRITE share value set. Thus it cannot succeed with other open attempts.

 

So the question would be is the something in the above target that is inappropriate for current access? Nothing that I have tried alters that Retrying class is in use.

Comments:
deleteOldFileOnStartup options

Reported in the forum at post: http://nlog-project.org/forum.html#nabble-tc1686002|a1686002

Hi

It seems that deleteOldFileOnStartup somehow make logger to erase fist few lines from the file including for example header.

This is a config file

As long as deleteOldFileOnStartup is true, the +++++++++++++ never appears in the log file (along with some of the program info which is logged by Main().

Here are examples of log file

deleteOldFileOnStartup="false"

+++++++++++++
22/10/2008 11:32:48| INFO| 10|---------------------------------------------
22/10/2008 11:32:48| INFO| 10|RB: App starts
22/10/2008 11:32:48| INFO| 10|---------------------------------------------
22/10/2008 11:32:50| INFO| 10|RB: DropDownList: executing prSelect
22/10/2008 11:32:51| INFO| 10|RB: DropDownList: executing prProcessView_Select
...

deleteOldFileOnStartup="true"

22/10/2008 11:34:08| INFO| 10|RB: DropDownList: executing prSelect
22/10/2008 11:34:08| INFO| 10|RB: DropDownList: executing prProcessView_Select
....

Cheers, Igor

NLogBugTroll wrote Oct 6 2009 at 10:02 PM

Testing indicates that the following option is what impacts this.

deleteOldFileOnStartup="true"

Although conceptually easy to understand why this causes a problem it means that functionality is lost particularly when it is AppDomains rather than actual different processes in use

Make Log events Serializable

in Log4net, the remoting appender sends a log event to the server. This is the kind of behavior I'm looking for in nlog. I could write my own target, but unless the log events are serializable, there's no way to send them up to the server.

(by the way, I'd go ahead and use Log4net and create my own appender, but there are no fallback mechanisms supported in Log4net yet as there is in NLog - good job on that.)

Moved from http://nlog.codeplex.com/workitem/2323

BufferingTargetWrapper can cause unhandled thread exception

The BufferedWrapper utilizes a timer to write to it's target, but does not have any error handling in the timer callback. This can cause an unhandled thread exception if the target gives an error. AsyncTargetWrapper has better handling, it should be simple to add the same code to BufferingTargetWrapper.

 

We have encountered this in a production Windows service, where we have a BufferedWrapper wrapping a MailTarget (which I would guess is a common configuration). It is relatively easy for a MailTarget to error out unexpectedly, e.g. mailbox full or some transitory network issue. In production, this error took down the service.

 

As a workaround, it does not help to wrap the async around the buffer, although I expect it would work ok if we wrapped the buffer around the async.

NLog 2 Beta 1 - Database Target - connectionString/dbProvider & connectionStringName/providerName

I got the exception --- System.ArgumentException: Expecting non-empty string for 'providerInvariantName' parameter --- while using the database target in NLog 2 Beta 1 against sql server. I kept getting that error despite setting connectionStringName to a valid connection name and the dbProvider to 'sqlserver'.

 

Upon code debug I saw that when 'connectionStringName' is set, the 'dbProvider' is ignored. Instead the 'providerName' attribute of the connection element is read. So it needs to be set like this:

<connectionStrings>

<add name="loggerSqlConn" providerName="System.Data.SqlClient" connectionString="Data Source=machinename\sqlexpress;Initial Catalog=dotnetlogs;Integrated Security=SSPI;Persist Security Info=False;"/>

</connectionStrings>

 

In this case, the providerName should always be the provider invariant name such as System.Data.SqlClient, Oracle.DataAccess.Client, System.Data.SQLite - etc. Trying to use short tokens will throw -- System.ArgumentException: Unable to find the requested .Net Framework Data Provider. It may not be installed.

 

If my analysis is correct, please add this bit of information to the documentation and it would save others lots of time

 

Vickram

Moved from http://nlog.codeplex.com/workitem/5419

EventLog target throws exception when no source is registered

NLog throws an exception when trying to write to the EventLog when no source for the process is registered.

This typically happens when one installs a windows service using installutil without adding an eventsource to the registry.

Or when debugging a WCF Service without runnig Visual Studio as admin.

 

This exception should only be thrown when throwExceptions="true".

 

[SecurityException: The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security.]

System.Diagnostics.EventLog.FindSourceRegistration(String source, String machineName, Boolean readOnly, Boolean wantToCreate) +664

System.Diagnostics.EventLog.SourceExists(String source, String machineName, Boolean wantToCreate) +109

System.Diagnostics.EventLog.SourceExists(String source, String machineName) +6

NLog.Targets.EventLogTarget.CreateEventSourceIfNeeded() +559

NLog.Targets.EventLogTarget.InitializeTarget() +38

NLog.Targets.Target.Initialize() +250

NLog.Config.LoggingConfiguration.InitializeAll() +841

NLogC Needs embedded manifest

Imported from SF.NET (1907202) https://sourceforge.net/tracker/?func=detail&aid=1907202&group_id=116456&atid=675007

 

Recent changes to Windows will prevent the MSVCR80.dll and MSVCM80.dll from being loaded. This is related to the Windows side by side mechanism and the requirement for embedding manifests for Windows to resolve references.

 

Rebuilding NLog, in VS8 or above, with the embedded manifest option checked will resolve these issues.

 

-Scott

Moved from http://nlog.codeplex.com/workitem/2319

LogReceiverService: Not able to use Credentials

When i need to use Credentials ( like in wsHttpBinding - Connection ) there is no way to set them ( only endpointAdress and enpointConfigurationName are available )..

Workaround is sth. like this:

var client = new WcfLogReceiverClient("WSHttpBinding_ILogReceiverServer");
client.ClientCredentials.UserName.UserName = "demo";
client.ClientCredentials.UserName.Password = "demo";
client.ProcessLogMessagesAsync(new NLogEvents());

Moved from http://nlog.codeplex.com/workitem/6529

NLog and MEF

Hello,

 

I am wondering what is the best way to use NLog with Managed Extensibility Framework (MEF)?

 

I have an application that support plugins using MEF architecture (Import and Exports etc)

I want to add logging capability to my application.

As a logging component I want to use NLog.

What would you recommend?

1. Create a wrapper for NLog, i.e. additional plugin that configures NLog and exports functions like void Log(string level, string message) that other plugins importing

2. Every plugin should have it is own instance of NLog configured and used. (They all would write to the same file actually).

NLogC printf()

Reported in the forum at post: http://nlog-project.org/forum.html#nabble-tc1685757|a1685757

 

I have a question bout the printf () style parameter usage mentioned in http://www.nlog-project.org/capi.html

 

I tried the following c-code:

 

int e = 4;

char f[] = "foo";

NLog_Info("", "f=%s e=%d", f, e);

 

which, in my opinion, should result in a log entry like:

 

2008-09-29 10:10:35.6978 Info f=foo e=4

 

but the logfile says:

 

2008-09-29 10:10:35.6978 Info f=f=%s e=%d e=1244308

 

 

 

What happend?

 

/erik

Method overloads

Please add overloads for logging methods with exception as parameter. Example:

 

void Warning(string msg, Exception err);

 

Looks much cleaner and "WarningException"

Getting strange System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Reported in the forum at post: http://nlog-project.org/forum.html#nabble-td1695060|a1695060

 

NLog is throwing an exception, which it shouldn't ever do. Looking at the source it seems to be part of the get stack trace code, even tho I don't think i'm using the stack trace renderer (i'm working to confirm that, though). Has anyone ever gotten this error in NLog? I'm at the point that I'm going to have to rip out NLog and put in log4net, and I REALLY don't want to have to do that.

 

This is the stack trace:

 

System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

at NLog.LoggerImpl.Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)

at NLog.Logger.WriteToTargets(LogLevel level, String message, Object[] args)

at NLog.Logger.Info(String message, Object argument)

at EmpathyLab.Util.Schema.Transform.TaskContainer.Run(DbConnectionHolder holder, Transformer transform) in c:\TeamCity\buildAgent\work\304d4dce34ae1ec1\EL.Util\Schema\Transform\TaskContainer.cs:line 53

at EmpathyLab.Util.Schema.Transform.Target.Run(DbConnectionHolder holder, Transformer t) in c:\TeamCity\buildAgent\work\304d4dce34ae1ec1\EL.Util\Schema\Transform\Target.cs:line 26

at EmpathyLab.Util.Schema.Transform.Transformer.RunTarget(DbConnectionHolder db, String targetName, Boolean rerun) in c:\TeamCity\buildAgent\work\304d4dce34ae1ec1\EL.Util\Schema\Transform\Transformer.cs:line 62

at EmpathyLab.Util.Schema.Transform.Transformer.RunTargets(DbConnectionHolder db, String[] targetsToRun, Boolean rerun) in c:\TeamCity\buildAgent\work\304d4dce34ae1ec1\EL.Util\Schema\Transform\Transformer.cs:line 71

at EmpathyLab.Util.Schema.Transform.Target.Run(DbConnectionHolder holder, Transformer t) in c:\TeamCity\buildAgent\work\304d4dce34ae1ec1\EL.Util\Schema\Transform\Target.cs:line 26

at EmpathyLab.Util.Schema.Transform.Transformer.RunTarget(DbConnectionHolder db, String targetName, Boolean rerun) in c:\TeamCity\buildAgent\work\304d4dce34ae1ec1\EL.Util\Schema\Transform\Transformer.cs:line 62

at EmpathyLab.Util.Schema.Transform.Transformer.RunTarget(String targetName, Boolean rerun) in c:\TeamCity\buildAgent\work\304d4dce34ae1ec1\EL.Util\Schema\Transform\Transformer.cs:line 40

at TBC.TK.Web.Global.Application_Start(Object sender, EventArgs e) in c:\TeamCity\buildAgent\work\304d4dce34ae1ec1\TBC.TK.Web\Global.asax.cs:line 106

Comments:
I am also seeing System.AccessViolationException Attempted to read or write protected memory, generated by NLog 2 Beta 1.
Exceptions are raised inside an IE7 BHO add-on I am developing in visual studio 2010.

When I disable logging, code works fine. When I enable logging code crashes every time.
Crash happens on Windows XP 32 SP3 + IE7
I am targeting .net 2.

Crash does not happen on another machine - Windows 7 64bit + IE8 works fine.

In my case, crash never includes a stack trace, not even under debugger.

Archiving doesn't work with .NET CF

I'm trying to use archiving for a Windows Mobile 6.1 application [.NET CF]

 

The normal logging works perfectly, but when trying to enable archiving, it doesn't archive at all, it just save all the log files as a normal log files in the normal log location.

 

My Code is:

 

FileTarget fileTarget = new FileTarget();

config.AddTarget("file", fileTarget);

fileTarget.FileName = @"/My Documents/Logger/Logs/${shortdate}.txt";

fileTarget.Layout = "${date:format=dd\\ MMM-HH\\:mm\\:ss} [${level:uppercase=true}] ${message}";

fileTarget.ConcurrentWrites = true;

fileTarget.ArchiveFileName = @"/My Documents/Logger/Logs/Archive/Log{#}.txt";

fileTarget.ArchiveNumbering = FileTarget.ArchiveNumberingMode.Sequence;

fileTarget.ArchiveEvery = FileTarget.ArchiveEveryMode.Day;

fileTarget.MaxArchiveFiles = 7;

 

I tried archiving every day with max archive files 7 files "as in the previous code,

And I tried archiving every month with max archive files 30 files

None of them worked, it just continue to add log files to the normal place with the normal log naming.

Moved from http://nlog.codeplex.com/workitem/5349

Exception: Cannot access a closed file

Application is a WebService based on ASP.NET 3.5.

 

It seems that when we do excessive logging (LogLevel Trace) with multiple threads to the WebService, NLog throws an Exception:

 

Cannot access a closed file.

at System.IO.__Error.FileNotOpen()

at System.IO.FileStream.Flush()

at System.IO.FileStream.get_SafeFileHandle()

at NLog.Internal.FileAppenders.MutexMultiProcessFileAppender.GetFileInfo(DateTime& lastWriteTime, Int64& fileLength)

at NLog.Targets.FileTarget.GetFileInfo(String fileName, DateTime& lastWriteTime, Int64& fileLength)

at NLog.Targets.FileTarget.ShouldAutoArchive(String fileName, LogEventInfo ev, Int32 upcomingWriteSize)

at NLog.Targets.FileTarget.Write(LogEventInfo logEvent)

at NLog.LoggerImpl.Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)

at NLog.Logger.WriteToTargets(LogLevel level, String message)

at NLog.Logger.Debug(String message)

 

We use "programmatic" configuration:

 

LoggingConfiguration config = new LoggingConfiguration();

 

FileTarget debugTarget = new FileTarget();

config.AddTarget("debug", debugTarget);

 

debugTarget.FileName = "${basedir}/Log.txt";

debugTarget.Layout = @"[${date:format=yyyy\.MM\.dd HH\:mm\:ss\:fff}]" + \t[${processid:fixedLength=True:padding=5:padCharacter= }]\t[${threadid:fixedLength=True:padding=5:padCharacter= }]\t[${aspnet-sessionid:fixedLength=True:padding=5:padCharacter= }]\t[${level:upperCase=True}] [${callsite:fileName=True:className=False:methodName=True:includeSourcePath=False}]\t ${message} ${exception:format=GetLocations,Message,StackTrace:separator=\n}";

 

// Limit file size we retain

debugTarget.ArchiveAboveSize = 10240000;

debugTarget.MaxArchiveFiles = 10;

 

debugTarget.KeepFileOpen = true;

debugTarget.Header = "\r\nTime\tProcessID\tThreadID\tASP.NET Session ID\tLogLevel\tCallSite\tMessage/Exception";

debugTarget.ConcurrentWrites = true;

 

AsyncTargetWrapper wrapper = new AsyncTargetWrapper();

wrapper.WrappedTarget = debugTarget;

wrapper.QueueLimit = 5000;

wrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Block;

NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(wrapper, LogLevel.Trace);

LoggingRule rule1 = new LoggingRule("*", LogLevel.Trace, debugTarget);

config.LoggingRules.Add(rule1);

 

LogManager.Configuration = config;

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.