@manhng

Welcome to my blog!

Simple Logger (NLog)

November 8, 2019 13:42

Simple Logger with NLog (edit)

Logger.cs

public static class Utils
{
    public static void WriteLog(string msg)
    {
        try
        {
            //Path log folder
            string folder = GetDesktopFolder();

            //Path log file
            string path = folder + "\\MyApp.log";

            // This text is added only once to the file.
            if (!File.Exists(path))
            {
                // Create a file to write to.
                using (StreamWriter sw = File.CreateText(path))
                {
                    sw.WriteLine(msg);
                }
            }

            // This text is always added, making the file longer over time
            // if it is not deleted.
            using (StreamWriter sw = File.AppendText(path))
            {
                sw.WriteLine(msg);
            }
        }
        catch (Exception e)
        {
            Debug.WriteLine("Exception: " + e.ToString());
        }
        finally
        {
            Debug.WriteLine("Executing finally block.");
        }
    }

    public static string GetDesktopFolder()
    {
        string strDesktopFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        return strDesktopFolderPath;
    }
}

Program.cs

try
{
    Utils.WriteLog("Program called.");
    Utils.WriteLog(string.Format("Start time: {0}", (start != null ? start.ToString() : "NULL")));
    Utils.WriteLog(string.Format("End time: {0}", (end != null ? end.ToString() : "NULL")));
}
catch
{

}

NLog in ASP.NET Web API 2.1

https://code-maze.com/net-core-web-development-part3/

https://www.c-sharpcorner.com/article/introduction-to-nlog-with-asp-net-core2/

https://github.com/jignesht24/Aspnetcore/tree/master/Logging%20with%20.net%20core%202.0/Using%20Nlog

https://dotnetthoughts.net/using-nlog-in-aspnet-core/

https://edi.wang/post/2017/11/1/use-nlog-aspnet-20

https://www.c-sharpcorner.com/article/introduction-to-nlog-with-asp-net-core2/ (NLog with .NET Core)

  1. Install-Package NLog
  2. Install-Package NLog.Web.AspNetCore

 <PackageReference Include="NLog.Web.AspNetCore" Version="4.5.4" />

<PackageReference Include="NLog" Version="4.5.4" />

1./ File nlog.config

<?xml version="1.0"?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="Warn"
internalLogFile="c:\temp\internal-nlog.txt">

<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>

<targets>
<target name="allfile" xsi:type="File"
fileName="${basedir}\Logging\${shortdate}.log"
encoding="utf-8"
layout="[${longdate}][${machinename}][${level}] ${message} ${exception}" />
</targets>
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />

<!--Skip Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>

2./ Config in Program.cs

public class Program  
{  
    public static void Main(string[] args)  
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>  
        WebHost.CreateDefaultBuilder(args)  
            .UseStartup()  
            .ConfigureLogging(logging =>  
            {  
                logging.ClearProviders();  
                logging.SetMinimumLevel(LogLevel.Information);  
            })  
            .UseNLog();  
}

3./ Using NLog in ValuesController

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Threading.Tasks;

namespace AspNetCoreWebApi.Controllers
{
[ApiController]
public class ValuesController : ControllerBase
{
private readonly ILogger<ValuesController> _logger;

public ValuesController(ILogger<ValuesController> logger)
{
_logger = logger;

_logger.LogInformation("ValuesController called.");
}
}

Reference

.NET Core

https://www.c-sharpcorner.com/article/net-core-web-api-logging-using-nlog-in-text-file/

https://www.c-sharpcorner.com/article/how-to-archive-log-files-using-nlog-with-asp-net-core/

https://www.c-sharpcorner.com/article/net-core-web-api-logging-using-nlog-in-event-log/

https://www.c-sharpcorner.com/article/combine-nlog-and-kafka-to-collect-logging-message-in-asp-net-core/

https://www.c-sharpcorner.com/article/introduction-to-nlog-with-asp-net-core2/

.NET

https://www.codeproject.com/Tips/1119363/Flexible-Logging-using-log-net

https://michaelscodingspot.com/logging-in-dotnet/

https://www.infoworld.com/article/2980677/implement-a-simple-logger-in-c.html

https://www.codeproject.com/Articles/1214072/A-Simple-Asynchronous-Logger-in-Csharp

https://www.codeproject.com/Tips/585796/Simple-Log

https://github.com/jirkapenzes/SimpleLogger

https://raygun.com/blog/c-sharp-logging-best-practices/

https://www.scalyr.com/blog/get-started-quickly-csharp-logging/

Categories

Recent posts