Folytassuk tovább a korábban elkezdett MVC-s projektünket, indítsuk el a Visual Studio-t, és olvassuk be a WebIotMVC projektünket. A kisebb méret (és a kezelhetőség miatt) a logolás eredményeit különböző szöveges file-okba mentjük el. Ehhez az NLog-ot fogjuk alkalmazni, de írhatunk akár mi is olyan osztályt/metódusokat, amelyeket meghívunk a mentés során. Az NLog (vagy akár a log4net) alkalmazásával azonban időt takaríthatunk meg, ezért nem készítünk saját eljárásokat a logolás megvalósítása során.
Az NLog telepítése legegyszerűbben a nuget oldalról tehető meg, írjuk be a böngészőbe a következő címet.
https://www.nuget.org
Ezután a nuget keresőjébe írjuk be az Nlog-ot, és a következő URL-en meg is találjuk a különböző találatokat.
https://www.nuget.org/packages?q=nlog
Kattintsunk a "Nlog"-ra, és következő URL-en meg is találjuk a letöltendő csomagot.
https://www.nuget.org/packages/NLog/
A letöltéshez (illetve a telepítéshez) ki kell adni azt a parancsot, amely ezen az ooldalon található meg. Ehhez azonban a Visual Studioban el kell indítanunk a Package Manager Console-t.
Install-Package NLog -Version 4.7.5
A "Package Manager Console" ablak a Visual Studioban található, a "Tools/NuGet Package Manager" menüpon alatt (1. ábra).
1. ábra Az NLog nuget telepítése a Package Manager Console ablakban
Ezután adjunk hozzá a projektünkhöz egy config file-t (2. ábra), amelynek a neve NLog.config legyen. Ebben a file-ban definiáljuk a létrehozandó config file-ok neveit, illetve a létrehozásuk helyét.
2. ábra Az Nlog.config file hozzáadása a projekthez
A projekthez hozzáadott NLog.config file tartalmát módosítsuk a következő példa szerint.
<?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"
autoReload="true"
internalLogLevel="Info"
internalLogFile="c:\logs\internal-nlog.txt">
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<targets>
<target xsi:type="File" name="allfile" fileName="c:\logs\nlog-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
<target xsi:type="File" name="ownFile-web" fileName="c:\logs\nlog-own-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="allfile" />
<logger name="Microsoft.*" maxlevel="Info" final="true" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>
A 3. ábrán látható a módosított WebIoTMVC projektünk felépítése a Visual Studio Solution Explorer ablakában..
3. ábra Projektünk felépítése a Solution Explorerben
Most töltsük be azokat az action-öket az iotControllerből, amelyeknek a futtatását szeretnénk logolni, és módosítsuk ezeknek a tartalmát. Töltsük be például az iotController "Index" actionjét, és módosítsuk a következő minta alapján. A módosítások döntött betűkkel kerültek megjelenítésre.
private static Logger logger = LogManager.GetCurrentClassLogger();
public IConfiguration Configuration { get; }
List<meresModell> lista;
string connectionString = null;
public iotController(IConfiguration configuration)
{
Configuration = configuration;
lista = new List<meresModell>();
connectionString = Configuration["ConnectionStrings:DefaultConnection"];
}
// GET: iotController
public ActionResult Index()
{
logger.Trace("Trace logolás");
logger.Info("Info logolás");
logger.Error("Error logolás");
logger.Log(LogLevel.Info, "Elindult az alkalmazás");
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "Select * from teszt";
SqlCommand command = new SqlCommand(sql, connection);
using (SqlDataReader dataReader = command.ExecuteReader())
{
while (dataReader.Read())
{
meresModell mm = new meresModell();
mm.id = Convert.ToInt32(dataReader["Id"]);
mm.hely = Convert.ToString(dataReader["Hely"]);
mm.ertek = Convert.ToInt32(dataReader["Ertek"]);
mm.ido = Convert.ToDateTime(dataReader["Datum"]);
lista.Add(mm);
}
}
connection.Close();
}
return View(lista);
}
// GET: iotController/Details/5
public ActionResult Details(int id)
{
meresModell mm = new meresModell();
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "Select * from teszt Where Id = '" + id + "' ";
SqlCommand command = new SqlCommand(sql, connection);
using (SqlDataReader dataReader = command.ExecuteReader())
{
while (dataReader.Read())
{
mm.id = Convert.ToInt32(dataReader["Id"]);
mm.hely = Convert.ToString(dataReader["Hely"]);
mm.ertek = Convert.ToInt32(dataReader["Ertek"]);
mm.ido = Convert.ToDateTime(dataReader["Datum"]);
}
}
connection.Close();
}
logger.Info("Megjelenítésre került a {0}. adat.", id);
return View(mm);
}
Futtassuk most párszor az alkalmazásunkat, és nézzük meg a "C:\Logs" könyvtár tartalmát (4. ábra). Látható, hogy több logfile is keletkezni fog a projektünk futtatásakor, amelyek a "C:\Logs" könyvtárban kerülnek majd elmentésre.
4. ábra Létrejöttek a különböző log file-ok a "Logs" könyvtárban
Ha megnézzük a log file-ok tartalmát, akkor könnyen észrevehetjük azt, hogy ezek a file-ok nem kerülnek törlésre (és újra létrehozásra), hanem az újabb log eredmények hozzáírásra kerülnek a korábbi eredményekhez.
nlog-all-2020-11-19.log file tartalma
2020-11-19 16:22:43.8121||TRACE|WebIoTMVC.Controllers.iotController|logTrace
2020-11-19 16:22:43.9100||INFO|WebIoTMVC.Controllers.iotController|logInfo
2020-11-19 16:22:43.9100||ERROR|WebIoTMVC.Controllers.iotController|logError
2020-11-19 16:22:43.9100||INFO|WebIoTMVC.Controllers.iotController|Sample informational message
2020-11-19 16:28:31.5469||TRACE|WebIoTMVC.Controllers.iotController|Trace logolás
2020-11-19 16:28:31.6308||INFO|WebIoTMVC.Controllers.iotController|Info logolás
2020-11-19 16:28:31.6308||ERROR|WebIoTMVC.Controllers.iotController|Error logolás
2020-11-19 16:28:31.6308||INFO|WebIoTMVC.Controllers.iotController|Elindult az alkalmazás
2020-11-19 16:28:37.1915||INFO|WebIoTMVC.Controllers.iotController|Megjelenítésre került a 3. adat.
2020-11-19 16:28:43.6759||TRACE|WebIoTMVC.Controllers.iotController|Trace logolás
2020-11-19 16:28:43.6759||INFO|WebIoTMVC.Controllers.iotController|Info logolás
2020-11-19 16:28:43.6867||ERROR|WebIoTMVC.Controllers.iotController|Error logolás
2020-11-19 16:28:43.6867||INFO|WebIoTMVC.Controllers.iotController|Elindult az alkalmazás
2020-11-19 16:28:46.1135||INFO|WebIoTMVC.Controllers.iotController|Megjelenítésre került a 6. adat.
2020-11-19 16:28:50.6713||TRACE|WebIoTMVC.Controllers.iotController|Trace logolás
2020-11-19 16:28:50.6713||INFO|WebIoTMVC.Controllers.iotController|Info logolás
2020-11-19 16:28:50.6864||ERROR|WebIoTMVC.Controllers.iotController|Error logolás
2020-11-19 16:28:50.6864||INFO|WebIoTMVC.Controllers.iotController|Elindult az alkalmazás
2020-11-19 16:45:48.4571||TRACE|WebIoTMVC.Controllers.iotController|Trace logolás
2020-11-19 16:45:48.5095||INFO|WebIoTMVC.Controllers.iotController|Info logolás
2020-11-19 16:45:48.5095||ERROR|WebIoTMVC.Controllers.iotController|Error logolás
2020-11-19 16:45:48.5136||INFO|WebIoTMVC.Controllers.iotController|Elindult az alkalmazás
2020-11-19 16:45:53.4980||INFO|WebIoTMVC.Controllers.iotController|Megjelenítésre került a 10. adat.
2020-11-19 16:45:56.2026||TRACE|WebIoTMVC.Controllers.iotController|Trace logolás
2020-11-19 16:45:56.2026||INFO|WebIoTMVC.Controllers.iotController|Info logolás
2020-11-19 16:45:56.2026||ERROR|WebIoTMVC.Controllers.iotController|Error logolás
2020-11-19 16:45:56.2180||INFO|WebIoTMVC.Controllers.iotController|Elindult az alkalmazás
2020-11-19 16:46:00.2506||INFO|WebIoTMVC.Controllers.iotController|Megjelenítésre került a 18. adat.
2020-11-19 16:46:03.0845||TRACE|WebIoTMVC.Controllers.iotController|Trace logolás
2020-11-19 16:46:03.0927||INFO|WebIoTMVC.Controllers.iotController|Info logolás
2020-11-19 16:46:03.0927||ERROR|WebIoTMVC.Controllers.iotController|Error logolás
2020-11-19 16:46:03.1063||INFO|WebIoTMVC.Controllers.iotController|Elindult az alkalmazás
2020-11-19 16:46:10.8890||INFO|WebIoTMVC.Controllers.iotController|Megjelenítésre került a 18. adat.
internal-nlog.txt file tartalma
2020-11-19 16:22:43.4328 Info Message Template Auto Format enabled
2020-11-19 16:22:43.4446 Info Loading assembly: NLog.Web.AspNetCore
2020-11-19 16:22:43.4589 Warn Error has been raised. Exception: NLog.NLogConfigurationException: Error loading extensions: NLog.Web.AspNetCore
---> System.IO.FileNotFoundException: Could not load file or assembly 'NLog.Web.AspNetCore, Culture=neutral, PublicKeyToken=null'. A rendszer nem találja a megadott fájlt.
File name: 'NLog.Web.AspNetCore, Culture=neutral, PublicKeyToken=null'
at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, RuntimeAssembly assemblyContext, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, AssemblyLoadContext assemblyLoadContext)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, StackCrawlMark& stackMark, AssemblyLoadContext assemblyLoadContext)
at System.Reflection.Assembly.Load(String assemblyString)
at NLog.Internal.AssemblyHelpers.LoadFromName(String assemblyName)
at NLog.Config.LoggingConfigurationParser.ParseExtensionWithAssembly(String assemblyName, String prefix)
--- End of inner exception stack trace ---
2020-11-19 16:22:43.6317 Info Adding target FileTarget(Name=allfile)
2020-11-19 16:22:43.6317 Error Error parsing layout aspnet-request-url will be ignored. Exception: System.ArgumentException: LayoutRenderer cannot be found: 'aspnet-request-url'. Is NLog.Web not included?
at NLog.Config.Factory`2.CreateInstance(String itemName)
at NLog.Layouts.LayoutParser.GetLayoutRenderer(ConfigurationItemFactory configurationItemFactory, String name, Nullable`1 throwConfigExceptions)
2020-11-19 16:22:43.6379 Error Error parsing layout aspnet-mvc-action will be ignored. Exception: System.ArgumentException: LayoutRenderer cannot be found: 'aspnet-mvc-action'. Is NLog.Web not included?
at NLog.Config.Factory`2.CreateInstance(String itemName)
at NLog.Layouts.LayoutParser.GetLayoutRenderer(ConfigurationItemFactory configurationItemFactory, String name, Nullable`1 throwConfigExceptions)
2020-11-19 16:22:43.6379 Info Adding target FileTarget(Name=ownFile-web)
2020-11-19 16:22:43.6942 Info Validating config: TargetNames=allfile, ownFile-web, ConfigItems=42, FilePath=C:\Users\timot\source\repos\WebIoTMVC\WebIoTMVC\bin\Debug\netcoreapp3.1\NLog.config
2020-11-19 16:22:43.7472 Info Configuration initialized.
2020-11-19 16:22:43.7995 Info NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.7.5.12092. Product version: 4.7.5+ed343d5690d9c97a96fcff430e240e2d7c31a8d7. GlobalAssemblyCache: False
2020-11-19 16:28:31.2477 Info Message Template Auto Format enabled
2020-11-19 16:28:31.2477 Info Loading assembly: NLog.Web.AspNetCore
2020-11-19 16:28:31.2653 Warn Error has been raised. Exception: NLog.NLogConfigurationException: Error loading extensions: NLog.Web.AspNetCore
---> System.IO.FileNotFoundException: Could not load file or assembly 'NLog.Web.AspNetCore, Culture=neutral, PublicKeyToken=null'. A rendszer nem találja a megadott fájlt.
File name: 'NLog.Web.AspNetCore, Culture=neutral, PublicKeyToken=null'
at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, RuntimeAssembly assemblyContext, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, AssemblyLoadContext assemblyLoadContext)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, StackCrawlMark& stackMark, AssemblyLoadContext assemblyLoadContext)
at System.Reflection.Assembly.Load(String assemblyString)
at NLog.Internal.AssemblyHelpers.LoadFromName(String assemblyName)
at NLog.Config.LoggingConfigurationParser.ParseExtensionWithAssembly(String assemblyName, String prefix)
--- End of inner exception stack trace ---
2020-11-19 16:28:31.4321 Info Adding target FileTarget(Name=allfile)
2020-11-19 16:28:31.4343 Error Error parsing layout aspnet-request-url will be ignored. Exception: System.ArgumentException: LayoutRenderer cannot be found: 'aspnet-request-url'. Is NLog.Web not included?
at NLog.Config.Factory`2.CreateInstance(String itemName)
at NLog.Layouts.LayoutParser.GetLayoutRenderer(ConfigurationItemFactory configurationItemFactory, String name, Nullable`1 throwConfigExceptions)
2020-11-19 16:28:31.4343 Error Error parsing layout aspnet-mvc-action will be ignored. Exception: System.ArgumentException: LayoutRenderer cannot be found: 'aspnet-mvc-action'. Is NLog.Web not included?
at NLog.Config.Factory`2.CreateInstance(String itemName)
at NLog.Layouts.LayoutParser.GetLayoutRenderer(ConfigurationItemFactory configurationItemFactory, String name, Nullable`1 throwConfigExceptions)
2020-11-19 16:28:31.4343 Info Adding target FileTarget(Name=ownFile-web)
2020-11-19 16:28:31.4735 Info Validating config: TargetNames=allfile, ownFile-web, ConfigItems=42, FilePath=C:\Users\timot\source\repos\WebIoTMVC\WebIoTMVC\bin\Debug\netcoreapp3.1\NLog.config
2020-11-19 16:28:31.5049 Info Configuration initialized.
2020-11-19 16:28:31.5260 Info NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.7.5.12092. Product version: 4.7.5+ed343d5690d9c97a96fcff430e240e2d7c31a8d7. GlobalAssemblyCache: False
2020-11-19 16:45:48.1724 Info Message Template Auto Format enabled
2020-11-19 16:45:48.1932 Info Loading assembly: NLog.Web.AspNetCore
2020-11-19 16:45:48.1932 Warn Error has been raised. Exception: NLog.NLogConfigurationException: Error loading extensions: NLog.Web.AspNetCore
---> System.IO.FileNotFoundException: Could not load file or assembly 'NLog.Web.AspNetCore, Culture=neutral, PublicKeyToken=null'. A rendszer nem találja a megadott fájlt.
File name: 'NLog.Web.AspNetCore, Culture=neutral, PublicKeyToken=null'
at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, RuntimeAssembly assemblyContext, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, AssemblyLoadContext assemblyLoadContext)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, StackCrawlMark& stackMark, AssemblyLoadContext assemblyLoadContext)
at System.Reflection.Assembly.Load(String assemblyString)
at NLog.Internal.AssemblyHelpers.LoadFromName(String assemblyName)
at NLog.Config.LoggingConfigurationParser.ParseExtensionWithAssembly(String assemblyName, String prefix)
--- End of inner exception stack trace ---
2020-11-19 16:45:48.3446 Info Adding target FileTarget(Name=allfile)
2020-11-19 16:45:48.3446 Error Error parsing layout aspnet-request-url will be ignored. Exception: System.ArgumentException: LayoutRenderer cannot be found: 'aspnet-request-url'. Is NLog.Web not included?
at NLog.Config.Factory`2.CreateInstance(String itemName)
at NLog.Layouts.LayoutParser.GetLayoutRenderer(ConfigurationItemFactory configurationItemFactory, String name, Nullable`1 throwConfigExceptions)
2020-11-19 16:45:48.3446 Error Error parsing layout aspnet-mvc-action will be ignored. Exception: System.ArgumentException: LayoutRenderer cannot be found: 'aspnet-mvc-action'. Is NLog.Web not included?
at NLog.Config.Factory`2.CreateInstance(String itemName)
at NLog.Layouts.LayoutParser.GetLayoutRenderer(ConfigurationItemFactory configurationItemFactory, String name, Nullable`1 throwConfigExceptions)
2020-11-19 16:45:48.3446 Info Adding target FileTarget(Name=ownFile-web)
2020-11-19 16:45:48.4035 Info Validating config: TargetNames=allfile, ownFile-web, ConfigItems=42, FilePath=C:\Users\timot\source\repos\WebIoTMVC\WebIoTMVC\bin\Debug\netcoreapp3.1\NLog.config
2020-11-19 16:45:48.4315 Info Configuration initialized.
2020-11-19 16:45:48.4470 Info NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.7.5.12092. Product version: 4.7.5+ed343d5690d9c97a96fcff430e240e2d7c31a8d7. GlobalAssemblyCache: False
Ebben a cikkben bemutatjuk a metódusok alapjait. Nem érintjük viszont például a túlterhelést, ezt egy következő részben tekintjük át.. . . .
A sorozatunknak ebben a részében átnézzük általánosságban az osztályok alapjait egy konzolalkalmazás segítségével. A konstruktorok viszont a következő részben kerülnek bemutatásra.. . . .
Ebben a cikkben nem csak a metódusok túlterhelését nézzük meg egy konkrét példa segítségével, hanem szóba kerülnek a generikusok is, szintén egy kisebb projekt keretén belül.. . . .