Obsivus
Obsivus

Reputation: 8359

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

Upvotes: 4

Views: 8165

Answers (4)

mexanoid
mexanoid

Reputation: 1

If you run your application in debug mode you can find it by this path:

"%PARTITION%:\\...PATH TO YOUR APP...\bin\Debug\\...

Upvotes: 0

madcyree
madcyree

Reputation: 1457

It's perfectly working, but ${basedir} for asp.net application isn't same as for typical desktop application. I believe this file is available from temporary folders, not far from your application assemblies.

You either can define your own variable or define a direct access to the 'logs' folder. Make sure that application can write logs into this folder. Use this answer, it's perfectly describe what you should do

Upvotes: 0

Jeff Ogata
Jeff Ogata

Reputation: 57783

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.

Upvotes: 6

mgnoonan
mgnoonan

Reputation: 7200

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.

Upvotes: 2

Related Questions