nlog threw NullReferenceException - nlog

I build project in Visual Studio for Mac. When project starting, Visual Studio threw NullReferenceException (Object reference not set to an instance of an object)
Stack trace: at NLog.Common.InternalLogger.GetSettingString
(System.String configName, System.String envName) [0x00006] in
:0 at
NLog.Common.InternalLogger.GetSetting[T] (System.String configName,
System.String envName, T defaultValue) [0x00001] in
:0 at
NLog.Common.InternalLogger..cctor () [0x0000b] in
:0
at NLog.LogFactory.GetConfigurationForLogger (System.String name,
NLog.Config.LoggingConfiguration configuration) [0x0004d] in
:0 at NLog.LogFactory.GetLogger
(NLog.LogFactory+LoggerCacheKey cacheKey) [0x00125] in
:0 at NLog.LogFactory.GetLogger
(System.String name) [0x00012] in :0
at NLog.LogManager.GetCurrentClassLogger () [0x0005f] in
:0 at
SM.App.Mac.AppDelegate..cctor () [0x00000] in
<5a4c63ba6bb041d195b1738f313e25e3>:0
at (wrapper managed-to-native)
MonoMac.AppKit.NSApplication:NSApplicationMain (int,string[]) at
MonoMac.AppKit.NSApplication.Main (System.String[] args) [0x0003d] in
:0 at SM.App.Mac.MainClass.Main
(System.String[] args) [0x00006] in
<5a4c63ba6bb041d195b1738f313e25e3>:0
Message: Object reference not set to an instance of an object
Source: NLog;
Platfrom: .Net 4.5
NLog Version : 4.4.12.
NLog Config:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="fatal" internalLogFile="${basedir}/logs/${shortdate}_internal.log">
<variable name="myvar" value="myvalue"/>
<targets>
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="f" />
</rules>
</nlog>

Related

Nlog Delete SQLite longer than X days

xsi:type="File" has maxArchiveFiles="5" archiveEvery="Day" properties. Is that possibble to delete db content older than X days?
xsi:type="Database" has rules for that purpose?
My sample Nlog.config;
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
throwConfigExceptions="true"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<targets>
<!--target name="logfile" xsi:type="File" fileName="file.txt" /!-->
<target xsi:type="Database"
name="db"
dbProvider="System.Data.SQLite.SQLiteConnection, System.Data.SQLite"
connectionString="Data Source=log.db3;"
commandType="Text"
commandText="INSERT into Log(Timestamp, Loglevel, Callsite, Message) values(#Timestamp, #Loglevel, #Callsite, #Message)"
>
<parameter name="#Timestamp" layout="${longdate}"/>
<parameter name="#Loglevel" layout="${level:uppercase=true}"/>
<parameter name="#Callsite" layout="${callsite:filename=true}"/>
<parameter name="#Message" layout="${message}"/>
</target>
<target name="colouredConsole" 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="Info" maxlevel="Info" writeTo="colouredConsole" />
<logger name="*" minlevel="Error" maxlevel="Error" writeTo="colouredConsole" />
<logger name="*" minlevel="Debug" maxlevel="Debug" writeTo="colouredConsole" />
<logger name="*" minlevel="Debug" maxlevel="Debug" writeTo="db" />
<logger name="*" minlevel="Error" maxlevel="Error" writeTo="db" />
</rules>
</nlog>
How to delete sqlite db content older than 7 days?
Some people suggests EnsureDb(); it works but I want to ask any possibility to set from xsi:type="Database" parameters?
private static void EnsureDb()
{
if (File.Exists("log.db3"))
{
using (SQLiteConnection connection = new SQLiteConnection("Data Source=log.db3"))
using (SQLiteCommand command = new SQLiteCommand(
"DELETE FROM Log WHERE Timestamp <= datetime('now', '-7 day');",
connection))
{
connection.Open();
command.ExecuteNonQuery();
}
return;
}
using (SQLiteConnection connection = new SQLiteConnection("Data Source=log.db3"))
using (SQLiteCommand command = new SQLiteCommand(
"CREATE TABLE Log (Timestamp TEXT, Loglevel TEXT, Callsite TEXT, Message TEXT)",
connection))
{
connection.Open();
command.ExecuteNonQuery();
}
}

dotnet core nlog running on Linux logs only one entry

I am running an aspnet core site on Linux using Kestrel. I have set up nlog to log to csv files. All is well in my Windows development environment, but when I run it on Linux I only get one entry in the log file. I turned on nlog tracing and found the following error in the output:
2016-09-09 07:22:46.2123 Error Error has been raised. Exception: System.IO.IOException: The file '/var/aspnetcore/CSWebSite/releases/20160909061254/logs/archives/own-log.20160908.csv' already exists.
at System.IO.UnixFileSystem.MoveFile(String sourceFullPath, String destFullPath)
at System.IO.File.Move(String sourceFileName, String destFileName)
at NLog.Targets.FileTarget.ArchiveByDate(String fileName, String pattern, LogEventInfo logEvent)
at NLog.Targets.FileTarget.ProcessLogEvent(LogEventInfo logEvent, String fileName, Byte[] bytesToWrite)
at NLog.Targets.FileTarget.FlushCurrentFileWrites(String currentFileName, LogEventInfo firstLogEvent, MemoryStream ms, List`1 pendingContinuations)
2016-09-09 07:22:46.2123 Error Error has been raised. Exception: System.IO.IOException: The file '/var/aspnetcore/CSWebSite/releases/20160909061254/logs/archives/all-log.20160907.csv' already exists.
at System.IO.UnixFileSystem.MoveFile(String sourceFullPath, String destFullPath)
at System.IO.File.Move(String sourceFileName, String destFileName)
at NLog.Targets.FileTarget.ArchiveByDate(String fileName, String pattern, LogEventInfo logEvent)
at NLog.Targets.FileTarget.ProcessLogEvent(LogEventInfo logEvent, String fileName, Byte[] bytesToWrite)
at NLog.Targets.FileTarget.FlushCurrentFileWrites(String currentFileName, LogEventInfo firstLogEvent, MemoryStream ms, List`1 pendingContinuations)
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">
<extensions>
<!--enable NLog.Web for ASP.NET Core-->
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<targets>
<!-- https://github.com/nlog/nlog/wiki/File-target -->
<!-- http://stackoverflow.com/questions/34679727/use-nlog-in-asp-net-5-application -->
<target name="allfile" xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
<target name="allfile" xsi:type="File"
fileName="${basedir}/logs/all-logfile.csv"
archiveFileName="${basedir}/logs/archives/all-log.{#}.csv"
archiveEvery="Day"
archiveNumbering="Date"
archiveDateFormat="yyyyMMdd"
maxArchiveFiles="28"
concurrentWrites="true"
keepFileOpen="false"
encoding="utf-8">
<layout xsi:type="CSVLayout">
<column name="time" layout="${longdate}" />
<column name="logger" layout="${logger}" />
<column name="authtype" layout="${aspnet-user-authtype}" />
<column name="identity" layout="${aspnet-user-identity}" />
<column name="level" layout="${uppercase:${level}}" />
<column name="message" layout="${message} ${exception:format=ToString,StackTrace}" />
</layout>
</target>
</target>
<target name="ownfile" xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
<target name="ownfile" xsi:type="File"
fileName="${basedir}/logs/own-logfile.csv"
archiveFileName="${basedir}/logs/archives/own-log.{#}.csv"
archiveEvery="Day"
archiveNumbering="Date"
archiveDateFormat="yyyyMMdd"
maxArchiveFiles="28"
concurrentWrites="true"
keepFileOpen="false"
encoding="utf-8">
<layout xsi:type="CSVLayout">
<column name="time" layout="${longdate}" />
<column name="logger" layout="${logger}" />
<column name="authtype" layout="${aspnet-user-authtype}" />
<column name="identity" layout="${aspnet-user-identity}" />
<column name="level" layout="${uppercase:${level}}" />
<column name="message" layout="${message} ${exception:format=ToString,StackTrace}" />
</layout>
</target>
</target>
<target xsi:type="Null" name="blackhole" />
</targets>
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Debug" writeTo="allfile" />
<!--Skip Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
<logger name="*" minlevel="Debug" writeTo="ownFile" />
</rules>
</nlog>
I have concurrent writes true and keepFileOpen false which seems necessary as kestrel forks multiple dotnet processes on Linux.
Is this a bug or is my configuration incorrect?

Check security header in Mule http:listener

I have a need to check some security HTTP header (called for example X-MyApp-Security) value before processing it after Mule http:listener. Header should be checked like basic auth header but more simply.
I found some Mule documentation about this but don't understand how to use it my simple flow:
<http:listener-config name="HTTP_Listener_Configuration" host="${httpServer.host}" port="${httpServer.port}" doc:name="HTTP Listener Configuration" />
<flow name="planadoWebhookFlow">
<http:listener config-ref="HTTP_Listener_Configuration" path="/" doc:name="HTTP" allowedMethods="POST"/>
<set-payload value="Hello from security area!" doc:name="Set Payload"/>
</flow>
Please help me with header authentication in Mule 3.7.
You can use the "http:basic-security-filter" element, here you have an example:
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns="http://www.mulesoft.org/schema/mule/core"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:scripting="http://www.mulesoft.org/schema/mule/scripting"
xmlns:http="http://www.mulesoft.org/schema/mule/http"
xmlns:jms="http://www.mulesoft.org/schema/mule/jms"
xmlns:vm="http://www.mulesoft.org/schema/mule/vm"
xmlns:file="http://www.mulesoft.org/schema/mule/file"
xmlns:ftp="http://www.mulesoft.org/schema/mule/ftp"
xmlns:db="http://www.mulesoft.org/schema/mule/db"
xmlns:mule-xml="http://www.mulesoft.org/schema/mule/xml"
xmlns:jersey="http://www.mulesoft.org/schema/mule/jersey"
xmlns:json="http://www.mulesoft.org/schema/mule/json"
xmlns:ws="http://www.mulesoft.org/schema/mule/ws"
xmlns:smtps="http://www.mulesoft.org/schema/mule/smtps"
xmlns:email="http://www.mulesoft.org/schema/mule/email"
xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:mule-ss="http://www.mulesoft.org/schema/mule/spring-security"
xmlns:ss="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/jms http://www.mulesoft.org/schema/mule/jms/current/mule-jms.xsd
http://www.mulesoft.org/schema/mule/vm http://www.mulesoft.org/schema/mule/vm/current/mule-vm.xsd
http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd
http://www.mulesoft.org/schema/mule/ftp http://www.mulesoft.org/schema/mule/ftp/current/mule-ftp.xsd
http://www.mulesoft.org/schema/mule/db http://www.mulesoft.org/schema/mule/db/current/mule-db.xsd
http://www.mulesoft.org/schema/mule/xml http://www.mulesoft.org/schema/mule/xml/current/mule-xml.xsd
http://www.mulesoft.org/schema/mule/jersey http://www.mulesoft.org/schema/mule/jersey/current/mule-jersey.xsd
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd
http://www.mulesoft.org/schema/mule/ws http://www.mulesoft.org/schema/mule/ws/current/mule-ws.xsd
http://www.mulesoft.org/schema/mule/smtps http://www.mulesoft.org/schema/mule/smtps/current/mule-smtps.xsd
http://www.mulesoft.org/schema/mule/email http://www.mulesoft.org/schema/mule/email/current/mule-email.xsd
http://www.mulesoft.org/schema/mule/spring-security http://www.mulesoft.org/schema/mule/spring-security/3.1/mule-spring-security.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
">
<spring:beans>
<ss:authentication-manager alias="authenticationManager">
<ss:authentication-provider>
<ss:user-service id="userService">
<ss:user name="user" password="password" authorities="ROLE_ADMIN" />
<ss:user name="anon" password="anon" authorities="ROLE_ANON" />
</ss:user-service>
</ss:authentication-provider>
</ss:authentication-manager>
</spring:beans>
<mule-ss:security-manager>
<mule-ss:delegate-security-provider name="memory-provider" delegate-ref="authenticationManager" />
</mule-ss:security-manager>
<http:listener-config name="HTTP_Listener_Configuration" host="localhost" port="9091" doc:name="HTTP Listener Configuration"/>
<flow name="testingFlow">
<http:listener config-ref="HTTP_Listener_Configuration" path="/*" doc:name="HTTP"/>
<logger message="Before Authentication" level="INFO" doc:name="Log Failure"/>
<http:basic-security-filter realm="mule-realm"/>
<logger message="After Authentication" level="INFO" doc:name="Log Failure"/>
</flow>
</mule>
You can find more information in the next link:
https://docs.mulesoft.com/mule-user-guide/v/3.7/http-listener-connector#authentication

Why are my exceptions not being logged with ServiceStack NLog?

Given this NLog config file:
<extensions>
<add assembly="Seq.Client.NLog"/>
</extensions>
<variable name="ServiceName" value="LO.Leads.Processor"/>
<targets async="true">
<target name="seq" xsi:type="Seq" serverUrl="http://mywebsite">
<property name="ThreadId" value="${threadid}" as="number" />
<property name="MachineName" value="${machinename}" />
</target>
<target name="file" xsi:type="File"
layout="${longdate}|${logger}|${level}|${threadid}|${message}"
fileName="C:\LogFiles\Leads\Processor\Processor.log"
archiveFileName="C:\LogFiles\Leads\Processor\Processor.{##}.log"
archiveEvery="Day"
archiveNumbering="Rolling"
maxArchiveFiles="45"
concurrentWrites="true"/>
<target name="debugger" xsi:type="Debugger"
layout="${logger}:${message}"/>
<target name="console" xsi:type="Console"
layout="${logger}:${level}:${threadid}:${message}" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="seq" />
<logger name="*" minlevel="Error" writeTo="file" />
<logger name="*" minlevel="Debug" writeTo="debugger" />
<logger name="*" minlevel="Debug" writeTo="console" />
</rules>
and this code block:
public class Program
{
static Program()
{
LogManager.LogFactory = new NLogFactory();
}
public static void Main()
{
HostFactory.Run(x =>
{
x.Service<ProcessorAppHost>(s =>
{
s.ConstructUsing(name => new ProcessorAppHost());
s.WhenStarted(ah =>
{
ah.Init();
ah.Start("http://*:8088/");
"Message processor listening at http://localhost:8088 ".Print();
});
s.WhenStopped(ah => ah.Dispose());
});
x.RunAsLocalSystem();
x.SetDescription("Processes all messages for the Leads application.");
x.SetDisplayName("Leads Message Processor");
x.SetServiceName("LOLeadsProcessor");
});
}
}
//MQHandlers
mqServer.RegisterHandler<LeadInformation>(m =>
{
try
{
var db = container.Resolve<IFrontEndRepository>();
db.SaveMessage(m as Message);
}
catch (Exception exception)
{
_log.Error("This is the only text logged", exception);
}
return ServiceController.ExecuteMessage(m);
});
and this exception
and here is the output from the 'file' logger
2014-11-11 10:06:53.9179|ProcessorAppHost|Error|24|This is the only text logged
Any idea about how to get the overloaded version of Error to work correctly?
Thank you,
Stephen
${message} contains the message of your exception, which is "This is the only text logged".
Take a look at the exception layout renderer.
layout="${longdate}|${logger}|${level}|${threadid}|${message}|${exception}"
Have you told ServiceStack to use NLog anywhere? e.g. before initializing your AppHost:
LogManager.LogFactory = new ServiceStack.Logging.NLogger.NLogFactory();
new AppHost().Init();

NLog is not writing to database table

This is my NLog Config file.
<?xml version="1.0" ?>
<nlog autoReload="true" throwExceptions="true" internalLogLevel="Debug" internalLogToConsole="true"
internalLogFile="c:\\temp\\nlog.txt"
>
<targets>
<!--Useful for debugging-->
<target name="consolelog" type="ColoredConsole"
layout="${date:format=HH\:mm\:ss}|${level}|${stacktrace}|${message}" />
<target name="filelog" type="File" fileName="c:\\temp\\nlog1.txt"
layout="${date}: ${message}" />
<target name="eventlog" type="EventLog" source="My App" log="Application"
layout="${date}: ${message} ${stacktrace}" />
<target name="databaselog" type="Database">
<dbProvider>sqlserver</dbProvider>
<!-- database connection parameters -->
<!-- alternatively you could provide a single 'connectionstring' parameter -->
<connectionString>Data Source=.\SQLEXPRESS;Initial Catalog=SnSolutions;User Id=sa;Password=test#1234#;</connectionString>
<!--<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=MyTest;User Id=mytest;Password=mytest123;" providerName="System.Data.SqlClient" />-->
<commandText>
insert into NLog_Error ([time_stamp],[level],[host],[type],1,[logger],[message],[stacktrace],[allxml]) values(#time_stamp,#level,#host,#type,#source,#logger,#message,#stacktrace,#allxml);
</commandText>
<parameter name="#time_stamp" layout="${date}" />
<parameter name="#level" layout="${level}" />
<parameter name="#host" layout="${machinename}" />
<parameter name="#type" layout="${exception:format=type}" />
<parameter name="#source" layout="${callsite:className=true:fileName=false:includeSourcePath=false:methodName=false}" />
<parameter name="#logger" layout="${logger}" />
<parameter name="#message" layout="${message}" />
<parameter name="#stacktrace" layout="${exception:stacktrace}" />
<parameter name="#allxml" layout="${web_variables}" />
</target>
</targets>
<rules>
<!--
<logger name="*" minlevel="Fatal" writeTo="eventlog" />
-->
<logger name="*" minlevel="Info" writeTo="filelog" />
<logger name="*" minlevel="Info" writeTo="databaselog" />
</rules>
</nlog>
This is my NLogLogger Class
public class NLogLogger
{
private readonly Logger _logger;
public NLogLogger(Logger logger)
{
_logger = logger;
}
public NLogLogger()
{
StackFrame frame = new StackFrame(1, false);
_logger = LogManager.GetLogger(frame.GetMethod().DeclaringType.FullName);
}
public void Trace(string message)
{
_logger.Trace(message);
}
public void Debug(string message)
{
_logger.Debug(message);
}
public void Info(string message)
{
_logger.Info(message);
}
public void Warn(string message)
{
_logger.Warn(message);
}
public void Error(string message)
{
_logger.Error(message);
}
public void Fatal(string message)
{
_logger.Fatal(message);
}
}
which I am trying to use in the following way.
NLogLogger logger = new NLogLogger();
logger.Info("We're on the Index page for Activities");
But not able to see any records in the DB nor any error in the File System.
Please let me know which is the part I am missing.
Thanks in advance.
You have an error in insert command - 1 is not a valid column name.
insert into NLog_Error (...[type],1,[logger]..)
Here is an example regarding logging to DB.

Resources