Mostafa
Mostafa

Reputation: 682

How log the client IP address with NLog in ASP.NET MVC

I made a portal with ASP.NET MVC and I need to log the IP address of any client that opens this website. I added NLog with NuGet to my project and I added below tags in Web.config:

  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
  </configSections>
  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
      <target name="default" xsi:type="File" fileName="logs/app-log.txt" archiveFileName="logs/archives/app-log.{#}.txt" archiveEvery="Day" archiveNumbering="Rolling" maxArchiveFiles="7" />
    </targets>
    <rules>
      <logger name="*" writeTo="default" />
    </rules>
  </nlog>

how set my application to log any other info in addition to IP address of any computer that registers data with my portal? Any help will be apprecited!

Upvotes: 3

Views: 2186

Answers (1)

Gowri Pranith Kumar
Gowri Pranith Kumar

Reputation: 1685

Layout on the target configuration can be modified to add the machine name and the Client IP address

layout="Machine Name: ${machinename} - IP: ${aspnet-request-ip}

More on this you can find here https://github.com/NLog/NLog/wiki/AspNet-Request-IP-Layout-Renderer

Edit: You may need NLog.Web for ASP.NET Web API and MVC projects. Also note that you may get ::1 as the IP address in the localhost but it works fine when hosted.

Upvotes: 4

Related Questions