Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I log a messages to a txt file with Nlog in MVC?

I am using Nlog in my MVC project

What I want to achieve is to log a message when a action method is executed in my controller. and the log message should appear on a txt file. But I cant seem to get it to work

I have installed Nlog to my references.

I've got Nlog.Config with following configuration:

<?xml version="1.0" ?>
<nlog 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="${longdate} ${logger} ${message}"
                fileName="${basedir}/logs/logfile.txt"
                keepFileOpen="false"
                encoding="iso-8859-2" />
    </targets>
    <rules>
        <logger name="*"
                minlevel="Debug"
                writeTo="file" />
    </rules>
</nlog>

and then inside my POST action method in my controller I have following code:

[HttpPost]
public ActionResult Edit(int id, CreateNKIphase1ViewModel model)
{
    Logger logger = LogManager.GetCurrentClassLogger();
    logger.Info("Test message");

     //code....
}

Where can I find the txt file?

Why is this not working :S

like image 486
Obsivus Avatar asked Feb 21 '23 11:02

Obsivus


2 Answers

If your application is running in IIS using an application pool identity, you will need to grant folder permissions to that identity.

  • Create the 'logs' folder.
  • In IIS Manager, find the app pool identity that your application is using.
  • In the 'logs' folder property dialog, grant write permission to the app pool identity.

When you enter the name for the app pool identity, you will need to include IIS APPPOOL. For example, if the app pool identity is ASP.NET v4.0, enter the name as IIS APPPOOL\ASP.NET v4.0. Also, make sure the location is the local machine, not a network domain.

like image 61
Jeff Ogata Avatar answered Mar 05 '23 09:03

Jeff Ogata


Why not set the fileName attribute to a known path and name, rather than using the ${basedir} format?

fileName="C:\Temp\logfile.txt"

That way you will know where the file is supposed to be. Once you have that part of the logging down, you can start adding in the more advanced techniques.

like image 43
mgnoonan Avatar answered Mar 05 '23 09:03

mgnoonan