Home > Mobile >  NLog is writing to Database, but not file
NLog is writing to Database, but not file

Time:07-05

I have these targets:

<target xsi:type="File" name="myAppLoggerTarget" fileName="${basedir}/logs/${shortdate}.log"
        layout="${longdate} ${uppercase:${level}} ${message}" />
<target xsi:type="Database"
    name="myAppLoggerTarget"
    connectionString="Data Source=R5-4500U\SQLEXPRESS;Initial Catalog=BlogDb;Integrated Security=True;"
    commandText="INSERT INTO Logs(CreatedOn,Message,Level,Exception,StackTrace,Logger,Url) VALUES (@datetime,@msg,@level,@exception,@trace,@logger,@url)">
        <parameter name="@datetime" layout="${date}" />
        <parameter name="@msg" layout="${message}" />
        <parameter name="@level" layout="${level}" />
        <parameter name="@exception" layout="${exception}" />
        <parameter name="@trace" layout="${stacktrace}" />
        <parameter name="@logger" layout="${logger}" />
        <parameter name="@url" layout="${aspnet-request-url}" />
</target>

And this rule:

<logger name="myAppLoggerRules" minlevel="Debug" writeTo="myAppLoggerTarget" />

For some reason when I call for example: GetLogger("myAppLoggerRules").Debug(message);, the log is only saved to the database, not the file.

When I comment out the database target, the file target works fine...

CodePudding user response:

I'm pretty sure you will need unique names on each target. So you code should be:

<target xsi:type="File" name="file" fileName="${basedir}/logs/${shortdate}.log"
        layout="${longdate} ${uppercase:${level}} ${message}" />
<target xsi:type="Database"
    name="database"
    connectionString="Data Source=R5-4500U\SQLEXPRESS;Initial Catalog=BlogDb;Integrated Security=True;"
    commandText="INSERT INTO Logs(CreatedOn,Message,Level,Exception,StackTrace,Logger,Url) VALUES (@datetime,@msg,@level,@exception,@trace,@logger,@url)">
        <parameter name="@datetime" layout="${date}" />
        <parameter name="@msg" layout="${message}" />
        <parameter name="@level" layout="${level}" />
        <parameter name="@exception" layout="${exception}" />
        <parameter name="@trace" layout="${stacktrace}" />
        <parameter name="@logger" layout="${logger}" />
        <parameter name="@url" layout="${aspnet-request-url}" />
</target>

...

<logger name="myAppLoggerRules" minlevel="Debug" writeTo="file" />
<logger name="myAppLoggerRules" minlevel="Debug" writeTo="database" />
  • Related