I have a .NET Core application which has NLog configured. This is the contents of the 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" autoReload="false" internalLogLevel="Error" internalLogToConsole="true" internalLogIncludeTimestamp="true" keepVariablesOnReload="true">
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<variable name="appId" value="" />
<variable name="componentId" value="" />
<variable name="file-target-path" value="" />
<variable name="file-target-name" value="" />
<targets>
<target xsi:type="Console" name="console-target" layout="${date:universalTime=true:format=yyyy-MM-dd HH\:mm\:ss.fff}Z ${uppercase:${level}} APP=${var:appId} COMP=${var:componentId} [${when:when='${threadname}'=='':inner=${threadid}:else=${threadname}}] ${message} - Logger=${logger},Level=${uppercase:${level}},ThreadId=${threadid},${onexception:,Exception\="${exception:format=tostring}"}" />
<target xsi:type="File" name="file-target"
layout="${date:universalTime=true:format=yyyy-MM-dd HH\:mm\:ss.fff}Z ${uppercase:${level}} APP=${var:appId} COMP=${var:componentId} [${when:when='${threadname}'=='':inner=${threadid}:else=${threadname}}] ${message} - Logger=${logger},Level=${uppercase:${level}},ThreadId=${threadid},${onexception:,Exception\="${exception:format=tostring}"}"
fileName="${basedir}/${var:file-target-path}/${var:file-target-name}.log"
archiveFileName="${basedir}/${var:file-target-path}/${var:file-target-name}.{###}.txt"
archiveEvery="Day"
archiveNumbering="DateAndSequence"
archiveAboveSize="5242880"
archiveDateFormat="yyyyMMdd"
maxArchiveDays="31" />
</targets>
<rules>
<logger name="*" minLevel="Trace" writeTo="console-target" />
<logger name="*" minLevel="Trace" writeTo="file-target" />
</rules>
</nlog>
I'm now writing a class which parses the log for a the Regex value \sApplication Running\s([\-]+?)\s. I currently have the log file path hard coded in my StreamReader like below:
Regex regex = new Regex(#"\sApplication Running\s([\-]+?)\s");
using (StreamReader reader = new StreamReader(#"C:\path\to\my\log_file.log"))
{
...
}
How can I update this so the log file is obtained from the logging configuration instead of the hard coding it in my class?
You can retrieve log file location from LogManager.Configuration.
var nlogFileTarget = LogManager.Configuration.AllTargets.OfType<FileTarget>().First();
var dummyEventInfo = new LogEventInfo { TimeStamp = DateTime.UtcNow };
var logFilePath = nlogFileTarget.FileName.Render(dummyEventInfo);
Similar solution:
<nlog>
<variable name="file-target-path" value="" />
<variable name="file-target-name" value="" />
<variable name="file-target-filename" value="${basedir}/${var:file-target-path}/${var:file-target-name}.log"" />
<targets>
<target xsi:type="File" name="file-target" fileName="${file-target-filename}" />
</targets>
<rules>
<logger name="*" minLevel="Trace" writeTo="file-target" />
</rules>
</nlog>
And then you can do this:
var filetargetPath = NLog.LogManager.Configuration?.Variables["file-target-filename"]?.Render(LogEventInfo.CreateNullEvent());
Related
my nlog not creating files. I Use the same configuration in another project and everythink is Ok, but in new project nlog not create new files.
Nlog config :
<?xml version="1.0" encoding="utf-8" ?>
autoReload= "true"
internalLogLevel =" Trace"
internalLogFile ="c:\temp\internal-nlog.txt">
<targets>
<target name="file" xsi:type="File"
layout="${longdate} ${logger} ${message}${exception:format=ToString}"
fileName="C:\beka\logs\logfile.txt"
/>
<target name="exceptions" xsi:type="File"
layout="${longdate} ${logger} ${message}${exception:format=ToString}"
fileName="C:\beka\logs\logfileExceptions.txt"
/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="file" />
<logger name="*" minlevel="Error" writeTo="exceptions" />
</rules>
On the console I can see that the log has been called but its not sent to a file.
I think the problem can be in c:\temp\internal-nlog.txt becouse this file has references to another project. And when i start another project internal-nlog.txt is update but when i start this project internal-nlog-txt doesnt update
Nlog action = content,
Copy to outputDirectory = copy if newer
I have a Graylog logging server set up for all our projects. One of the projects is using NLog and it uses a framework with Common Logging.
When the framework logs, the messsage received in Graylog is {0}. So somewhere it's string formatting not done.
If i configure a parameter and send in $(message) there, the expanded message is sent.
Also, the colored console configured works as expected.
<?xml version="1.0" encoding="utf-8" ?>
<nlog throwExceptions="true" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<extensions>
<add assembly="NLog.Targets.GraylogHttp"/>
</extensions>
<targets>
<target name="graylog" xsi:type="GraylogHttp" facility="Superman"
graylogServer="http://xxxxxx.stackhero-network.com" graylogPort="xxxx">
<parameter name="real_message" layout="${longdate}|${pad:padding=5:inner=${level:uppercase=true}}|${message}" />
<parameter name="source_method" layout="${callsite}" />
</target>
<target name="coloredConsole" xsi:type="ColoredConsole" useDefaultRowHighlightingRules="false"
layout="${longdate}|${pad:padding=5:inner=${level:uppercase=true}}|${message}" >
<highlight-row condition="level == LogLevel.Debug" foregroundColor="DarkGray" />
<highlight-row condition="level == LogLevel.Info" foregroundColor="Gray" />
<highlight-row condition="level == LogLevel.Warn" foregroundColor="Yellow" />
<highlight-row condition="level == LogLevel.Error" foregroundColor="Red" />
<highlight-row condition="level == LogLevel.Fatal" foregroundColor="Red" backgroundColor="White" />
</target>
</targets>
<rules>
<logger name="*" minlevel="Trace" appendTo="graylog"/>
<logger name="*" minlevel="Trace" appendTo="coloredConsole"/>
</rules>
</nlog>
The code used for calling looks like this (Relevant parts...)
using Common.Logging;
internal static ILog Logger = LogManager.GetLogger<SboApp>();
Logger.Error($"UI Connect Error: {ex.Message}", ex);
I'm using
Common.Logging.NLog4412 v 3.4.1
NLog v 4.4.12
NLog.Targets.GraylogHttp v 0.0.24
What am i doing wrong
I use NLog for debugging/tracing in my app. What's happening is that I am seeing some extra stuff in the output. This is C#/VisualStudio on the Mac, targeting iOS.
Here is an example...
I'm using a target of type "Debugger", and my layout line is:
<layout="${time} ${level} ${callsite}:${callsite-linenumber} ${message}"/>
The call to the logger is:
log.Debug("Added New Key. Code = {0}", code);
And the output is:
AppleLibrary.PasswordMgr: 16:04:36.4064 Debug
AppleLibrary.PasswordMgr.SavePassword:55 Added New Key. Code = -34018
Every debug line starts with <logger name>:
Its even worse when I use a target type of "Console" with exactly the same layout. A call like this:
log.Debug("Started Application");
ends up with this:
2017-06-14 16:04:23.673 MyApp.iOS[11942:6245589] 16:04:23.6374 Debug MyApp.iOS.Application.Main:14 Started Application
in this case every line starts with: 2017-06-14 16:04:23.673 MyApp.iOS[11942:6245589], which looks like the long date, logger name and thread/tick information.
Note that this does not happen with my file target, even though it uses exactly the same layout! The above call shows this in the logfile.txt:
16:04:23.6374 Debug MyApp.iOS.Application.Main:14 Started Application
Which is exactly what I want.
Here 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" throwExceptions="true">
<targets>
<target name="logfile"
xsi:type="File"
header="############STARTING RUN ${date} ${time}"
archiveOldFileOnStartup="true"
maxArchiveFiles="5"
fileName="/Users/Paul/Dev/MyApp/MyApp.iOS/logfile.txt"
layout="${time} ${level} ${callsite}:${callsite-linenumber} ${message}"/>
<target name="console" xsi:type="Console"
layout="${time} ${level} ${callsite}:${callsite-linenumber} ${message}"/>
<target name="debugger"
xsi:type="Debugger"
layout="${time} ${level} ${callsite}:${callsite-linenumber} ${message}"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="logfile" />
<logger name="CoreLibrary.*" minlevel="Trace" writeTo="debugger" enabled="false" />
<logger name="AppleLibrary.*" minlevel="Debug" writeTo="debugger" />
<logger name="MyApp.iOS.*" minlevel="Debug" writeTo="console" />
</rules>
</nlog>
I'd appreciate any pointers as to what I'm misunderstanding here.
Thanks.
Paul.
I have some console apps I've written at work. I'd like to get NLog into them but I am having trouble.
When I inspect the 'logger' object, I see in it's 'Factory' property, that the configuration had targets=0, loggingrules=0, everything blank or unset.
So, it doesn't do ANYTHING.. doesn't drop an internal log file either... I have tried nLog.config NLog.config and nlog.config... to no avail. Tried ver 3 and 4 of NLog too...
Why would it not pick up the config?
I have:
NLog.config in the root with 'Content' for build action and 'Copy Always' set
Confirmed the NLog.config IS being copied to the bin
Here's the 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"
autoReload="true"
throwConfigExceptions="true"
throwExceptions="true"
internalLogLevel="Trace"
internalLogFile="c:\temp\NlogInternal.log"
internalLogToConsole="true"
internalLogToConsoleError="true"
internalLogToTrace="true">
<targets>
<target xsi:type="Console" name="debugConsole" layout="${message} "/>
<target xsi:type="File" name="debugFile" createDirs="true" fileName="c:\temp\testlog.log" layout="${longdate} ${uppercase:${level}} ${message}"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="debugConsole"/>
<logger name="*" minlevel="Trace" writeTo="debugFile"/>
</rules>
</nlog>
and finally (this doesn't error, but nothing is output since the config is blank):
private static Logger logger = LogManager.GetCurrentClassLogger();
logger.Info("ConsoleApp test log...");
Do your app.config have a NLog configSection?
Something like this:
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog>
</nlog>
</configuration>
If even the internalLogger isn't working, you could debug the issue by setting
the InternalLogger.LogWriter
e.g.
// enable internal logging to a custom TextWriter
InternalLogger.LogWriter = new StringWriter(); //e.g. TextWriter writer = File.CreateText("C:\\perl.txt")
I got the same issue on my end. When you make change your fileName Path "c:\temp\testlog.log" to
"c:/temp/testlog.log" then it will work. Hope the below snipet help you to resolve the issue.
<targets>
<target xsi:type="Console" name="debugConsole" layout="${message} "/>
<target xsi:type="File" name="debugFile" createDirs="true"
fileName="c:/temp/testlog.log" layout="${longdate} ${uppercase:${level}}
${message}"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="debugConsole"/>
<logger name="*" minlevel="Trace" writeTo="debugFile"/>
</rules>
Using the default configuration for LogEntries, is it possible to create insert parameterized values into the layout?
<nlog>
<extensions>
<add assembly="LogentriesNLog" />
</extensions>
<targets>
<target name="logentries" type="Logentries" debug="true" httpPut="false" ssl="false" layout="${date:format=ddd MMM dd} ${time:format=HH:mm:ss} ${date:format=zzz yyyy} ${logger} {SOME PARAM FROM CONFIG} : ${LEVEL}, ${message}">
</target>
</targets>
<rules>
<logger name="*" minLevel="Trace" appendTo="logentries" />
</rules>
</nlog>
I'm an idiot sometimes.
You can just stick them in the layout string
<target name="logentries" type="Logentries" debug="true" httpPut="false" ssl="false" layout="${date:format=ddd MMM dd} ${time:format=HH:mm:ss} ${date:format=zzz yyyy} : ${LEVEL}, ${message}, ${SomeParam}"></target>