Как правильно настроить логирование в Nlog? - C#
Формулировка задачи:
ИСПОЛЬЗУЕТСЯ:
C#, Visual Studio 2015 Как сделать, чтобы каждое действие в программе записывалось в лог. ПРИМЕР. - клик по кнопке; - поиск элементов; - выполняется метод "метод 1"; - переменная "n" приняла значение "значение 1"; - ошибка "ошибка 1" и т.д. Всё описанный перечень описывается в файл с фиксирование даты и времени. Попробовал это реализовать в Nlog, но что-то не очень.КОД основного КЛАССА
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NLog; // добавлено
using NLog.Config; // добавлено
namespace rsh
{
public partial class Form1 : Form
{
// *** ЛОГЕР ***.
private static Logger logger = LogManager.GetCurrentClassLogger();
int r;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
r = 1 + 1;
textBox1.Text = r.ToString();
//Просто информация
logger.Trace("log {0}", this.Text);
logger.Debug("log {0}", this.Text);
logger.Info("log {0}", this.Text);
logger.Warn("log {0}", this.Text);
logger.Error("log {0}", this.Text);
logger.Fatal("log {0}", this.Text);
}
}
}КОД Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using NLog; // добавлено
using NLog.Config; // добавлено
namespace rsh
{
static class Program
{
// ЛОГЕР
private static Logger logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// Главная точка входа для приложения.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
// КОНФИГУРИРУЕМ ЛОГЕР
// NLog.Config.DOMConfigurator.Configure();
logger.Trace("logger.Trace");
logger.Debug("logger.Debug");
logger.Info("logger.Info");
logger.Warn("logger.Warn");
logger.Error("logger.Error");
logger.Fatal("logger.Fatal");
}
}
}ВОПРОС
1. Как можно логирование в приведённом мной формате? 2. Как можно логирование в приближённом формате к приведённом мной? 3. Как можно вообще правильно сделать логирование?PS
C# пока только осваиваю, поэтому прошу делать поправку на неточности в терминологии и постановке вопросаРешение задачи: «Как правильно настроить логирование в Nlog?»
textual
Листинг программы
<?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" >
<!-- optional, add some variabeles
[url]https://github.com/nlog/NLog/wiki/Configuration-file#variables[/url]
-->
<variable name="myvar" value="myvalue"/>
<!--
See [url]https://github.com/nlog/nlog/wiki/Configuration-file[/url]
for information on customizing logging rules and outputs.
-->
<targets>
<!--
add your targets here
See [url]https://github.com/nlog/NLog/wiki/Targets[/url] for possible targets.
See [url]https://github.com/nlog/NLog/wiki/Layout-Renderers[/url] for the possible layout renderers.
-->
<target name="console" xsi:type="Console" layout="${date:format=HH\:mm\:ss}|${level}|${message}" />
<target name="file"
xsi:type="File"
fileName="${basedir}/logs/Log.${level}.current.txt"
layout="${longdate} ${callsite} ${level}: ${message} ${exception:format=Message,StackTrace} ${stacktrace}"
archiveFileName="${basedir}/logs/archives/log.error.${shortdate}.{#}.txt"
archiveAboveSize="5242880"
archiveEvery="Day"
archiveNumbering = "Rolling"
maxArchiveFiles="3" />
<!--
Writing events to the a file with the date in the filename.
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
-->
</targets>
<rules>
<!-- add your logging rules here -->
<logger name="*" minlevel="Debug" writeTo="file" />
<logger name="*" minlevel="Trace" writeTo="file" />
<!--
Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f"
<logger name="*" minlevel="Debug" writeTo="f" />
-->
</rules>
</nlog>