locked
Nlog in c# RRS feed

  • Question

  • User-588203678 posted
    Using Nlog I need to write Jon file,text file and save to database.
    Thursday, October 10, 2019 1:28 PM

All replies

  • User475983607 posted

    Using Nlog I need to write Jon file,text file and save to database.

    Cool, do you have a question?

    Thursday, October 10, 2019 1:30 PM
  • User-588203678 posted
    Using Nlog namespace how to write log file,save to database and write in json file.
    Thursday, October 10, 2019 1:38 PM
  • User475983607 posted

    Using Nlog namespace how to write log file,save to database and write in json file.

    Can you be more specific? 

    This question involves the entire .NET stack.   Is there anyway you can share your code and explain the problems you are currently trying to solve?

    Thursday, October 10, 2019 1:50 PM
  • User-588203678 posted
    Using Nlog;
    Public class A
    (
    Try

    Logger a ;
    Int a =1;
    Int b=0;
    Int c = a/b
    Catch(exception ex)
    (
    Logger a;
    a.log("error",ex)
    )
    I want to write this exception in notepad,Json string and also save in database.
    Thursday, October 10, 2019 5:15 PM
  • User475983607 posted

    Using Nlog;
    Public class A
    (
    Try

    Logger a ;
    Int a =1;
    Int b=0;
    Int c = a/b
    Catch(exception ex)
    (
    Logger a;
    a.log("error",ex)
    )
    I want to write this exception in notepad,Json string and also save in database.

    And what happens?  Are you receiving an error?  Is the record written to SQL?  Is the JSON file created?  Where is your code???

    Thursday, October 10, 2019 5:54 PM
  • User-588203678 posted
    It is not writing into file.please help.
    Friday, October 11, 2019 1:09 AM
  • User-588203678 posted
    No error are thrown.
    Friday, October 11, 2019 1:10 AM
  • User-719153870 posted

    Hi guhananth1,

    To use NLog in your project, you will need to install two packages from your Nuget Packages: NLog package and NLog.Config package which will automatically generate a NLog.config file in your project.

    You can refer to NLog - Logging to a file and Logging To A File With NLog to see if you can build a demo to log into a file.

    For more information about NLog log, please refer to this tutorial.

    Below is my demo and generate a log file successfully.

    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="Off" internalLogFile="c:\temp\nlog-internal.log">
    
      <variable name="myvar" value="myvalue"/>
      <targets>
        <target name="fileTarget"
                xsi:type="File"
                fileName="C:\logs\example.log"
                layout="
    -------------- ${level} (${longdate}) --------------${newline}
    ${newline}
    Call Site: ${callsite}${newline}
    Exception Type: ${exception:format=Type}${newline}
    Exception Message: ${exception:format=Message}${newline}
    Stack Trace: ${exception:format=StackTrace}${newline}
    Additional Info: ${message}${newline}" />
      </targets>
    
      <rules>
        <logger level="Error" name="fileLogger" writeTo="fileTarget"/>
      </rules>
    </nlog>
    

    Program.cs:

    static void Main(string[] args)
            {
                try
                {
                    int zero = 0;
                    int result = 5 / zero;
                }
                catch (DivideByZeroException ex)
                {
                    Logger logger = LogManager.GetLogger("fileLogger");
                    logger.Error(ex, "Whoops!");
                }
            }
        }

    Here's the result:

    Best Regard,

    Yang Shen

    Friday, October 11, 2019 2:40 AM
  • User-588203678 posted
    Works good. How about writing to json file and save to database.
    Friday, October 11, 2019 4:33 AM
  • User-719153870 posted

    Hi guhananth1,

    Writing to a json file is exactly the same as writing to a notepad file.

    Please refer to Writing to JSON and below demo:

    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="Off" internalLogFile="c:\temp\nlog-internal.log">
    
      <variable name="myvar" value="myvalue"/>
      <targets>
        <target name="jsonFile" xsi:type="File" fileName="C:\logs\test.json">
          <layout xsi:type="JsonLayout">
            <attribute name="time" layout="${longdate}" />
            <attribute name="level" layout="${level:upperCase=true}"/>
            <attribute name="message" layout="${message}" />
          </layout>
        </target>
      </targets>
      <rules>
        <logger level="Error" name="jsonfileLogger" writeTo="jsonFile"/>
      </rules>
    </nlog>

    Program.cs:

    static void Main(string[] args)
            {
                try
                {
                    int zero = 0;
                    int result = 5 / zero;
                }
                catch (DivideByZeroException ex)
                {
                    Logger logger = LogManager.GetLogger("jsonfileLogger");
                    logger.Error(ex, "Whoops!");
                }
            }

    Here's the result:

    As for saving to database, it will need several things:

    • A connnection string in your App.config;
    • A database table;
    • A stored procedure to insert data;

    You can refer to NLog - Logging to a database along with Logging To A Database With NLog, you will find it's very easy too.

    Also, below is my another demo:

    App.config:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <startup>
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
        </startup>
      <connectionStrings>
        <!-- update this connection string to work for your database -->
        <add name="NLog" connectionString="Data Source=.;Initial Catalog=DatabaseTestPool;Integrated Security=True" providerName="System.Data.SqlClient" />
      </connectionStrings>
    </configuration>

    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="Off" internalLogFile="c:\temp\nlog-internal.log">
    
      <variable name="myvar" value="myvalue"/>
      <targets>
        <target name="database"
                xsi:type="Database"
                connectionStringName="NLog"
                commandText="exec dbo.InsertLog
                                @level,
                                @callSite,
                                @type,
                                @message,
                                @stackTrace,
                                @innerException,
                                @additionalInfo">
          <parameter name="@level" layout="${level}" />
          <parameter name="@callSite" layout="${callsite}" />
          <parameter name="@type" layout="${exception:format=type}" />
          <parameter name="@message" layout="${exception:format=message}" />
          <parameter name="@stackTrace" layout="${exception:format=stackTrace}" />
          <parameter name="@innerException"
                      layout="${exception:format=:innerFormat=ShortType,Message,Method:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}" />
          <parameter name="@additionalInfo" layout="${message}" />
        </target>
      </targets>
      <rules>
        <logger levels="Error,Warn,Fatal" name="databaseLogger" writeTo="database"/>
      </rules>
    </nlog>

    Program.cs:

    static void Main(string[] args)
            {
                try
                {
                    int zero = 0;
                    int result = 5 / zero;
                }
                catch (DivideByZeroException ex)
                {
                    Logger logger = LogManager.GetLogger("databaseLogger");
                    logger.Error(ex, "Whoops!");
                }
            }

    Here's the result:

    Hope this could help.

    Best Regard,

    Yang Shen

    Friday, October 11, 2019 5:54 AM
  • User-588203678 posted
    Can I do all operation on same Nlog.config
    Friday, October 11, 2019 7:08 AM
  • User753101303 posted

    Hi,

    Try https://github.com/nlog/nlog/wiki/Configuration-file and scroll down to "Rules".

    Seems you could use something such as

    <logger name="ExceptionLogger" writeTo="database,jsonfile" />

    So a logging destination sends the output to multiple targets...

    Friday, October 11, 2019 8:00 AM
  • User-719153870 posted

    Hi guhananth1,

    Please try below demo:

    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="Off" internalLogFile="c:\temp\nlog-internal.log">
    
      <variable name="myvar" value="myvalue"/>
      <targets>
        <target name="fileTarget"
                xsi:type="File"
                fileName="C:\logs\example.log"
                layout="
    -------------- ${level} (${longdate}) --------------${newline}
    ${newline}
    Call Site: ${callsite}${newline}
    Exception Type: ${exception:format=Type}${newline}
    Exception Message: ${exception:format=Message}${newline}
    Stack Trace: ${exception:format=StackTrace}${newline}
    Additional Info: ${message}${newline}" />
        <target name="database"
                xsi:type="Database"
                connectionStringName="NLog"
                commandText="exec dbo.InsertLog
                                @level,
                                @callSite,
                                @type,
                                @message,
                                @stackTrace,
                                @innerException,
                                @additionalInfo">
          <parameter name="@level" layout="${level}" />
          <parameter name="@callSite" layout="${callsite}" />
          <parameter name="@type" layout="${exception:format=type}" />
          <parameter name="@message" layout="${exception:format=message}" />
          <parameter name="@stackTrace" layout="${exception:format=stackTrace}" />
          <parameter name="@innerException"
                      layout="${exception:format=:innerFormat=ShortType,Message,Method:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}" />
          <parameter name="@additionalInfo" layout="${message}" />
        </target>
        <target name="jsonFile" xsi:type="File" fileName="C:\logs\test.json">
          <layout xsi:type="JsonLayout">
            <attribute name="time" layout="${longdate}" />
            <attribute name="level" layout="${level:upperCase=true}"/>
            <attribute name="message" layout="${message}" />
          </layout>
        </target>
      </targets>
    
      <rules>
        <logger level="Error" name="multiLogger" writeTo="database,jsonFile,fileTarget"/>
      </rules>
    </nlog>

    Program.cs:

    static void Main(string[] args)
            {
                try
                {
                    int zero = 0;
                    int result = 5 / zero;
                }
                catch (DivideByZeroException ex)
                {
                    Logger logger = LogManager.GetLogger("multiLogger");
                    logger.Error(ex, "Whoops!");
                }
            }

    This will save notepad, json and database at the same time.

    Best Regard,

    Yang Shen

    Friday, October 11, 2019 9:37 AM