Implemented logging. To complete the logging implementation I have to log the flow to the log file #16

This commit is contained in:
amazing-username
2019-05-05 12:09:19 -04:00
parent 649d2c75a3
commit 4a385af3b5
6 changed files with 126 additions and 52 deletions
+16 -7
View File
@@ -7,6 +7,7 @@ using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Icarus.Controllers.Managers; using Icarus.Controllers.Managers;
using Icarus.Controllers.Utilities; using Icarus.Controllers.Utilities;
@@ -20,6 +21,7 @@ namespace Icarus.Controllers
public class SongController : ControllerBase public class SongController : ControllerBase
{ {
#region Fields #region Fields
private readonly ILogger<SongController> _logger;
private IConfiguration _config; private IConfiguration _config;
private MusicStoreContext _context; private MusicStoreContext _context;
private SongManager _songMgr; private SongManager _songMgr;
@@ -31,10 +33,12 @@ namespace Icarus.Controllers
#region Constructor #region Constructor
public SongController(IConfiguration config) public SongController(IConfiguration config, ILogger<SongController> logger)
{ {
_config = config; _config = config;
_logger = logger;
_songMgr = new SongManager(config); _songMgr = new SongManager(config);
_logger.LogInformation("Logging is working!");
} }
#endregion #endregion
@@ -73,19 +77,24 @@ namespace Icarus.Controllers
[HttpPut("{id}")] [HttpPut("{id}")]
public IActionResult Put(int id, [FromBody] Song song) public IActionResult Put(int id, [FromBody] Song song)
{ {
// TODO: Implement updating of song metadata
MusicStoreContext context = HttpContext.RequestServices MusicStoreContext context = HttpContext.RequestServices
.GetService(typeof(MusicStoreContext)) as MusicStoreContext; .GetService(typeof(MusicStoreContext)) as MusicStoreContext;
song.Id = id;
Console.WriteLine("Retrieving filepath of song"); Console.WriteLine("Retrieving filepath of song");
var songPath = context.GetSong(id).SongPath; var oldSongRecord = context.GetSong(id);
song.SongPath = songPath; song.SongPath = oldSongRecord.SongPath;
MetadataRetriever updateMetadata = new MetadataRetriever(); MetadataRetriever updateMetadata = new MetadataRetriever();
updateMetadata.UpdateMetadata(song); updateMetadata.UpdateMetadata(song, oldSongRecord);
context.UpdateSong(song); var updatedSong = updateMetadata.UpdatedSongRecord;
context.UpdateSong(updatedSong);
SongResult songResult = new SongResult(); SongResult songResult = new SongResult
{
Message = updateMetadata.Message,
SongTitle = updatedSong.Title
};
return Ok(songResult); return Ok(songResult);
} }
+4
View File
@@ -22,10 +22,14 @@
<PackageReference Include="MySql.Data.EntityFrameworkCore" Version="8.0.15" /> <PackageReference Include="MySql.Data.EntityFrameworkCore" Version="8.0.15" />
<PackageReference Include="MySql.Data.EntityFrameworkCore.Design" Version="8.0.15" /> <PackageReference Include="MySql.Data.EntityFrameworkCore.Design" Version="8.0.15" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" /> <PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.8.1" />
<PackageReference Include="RestSharp" Version="106.6.9" /> <PackageReference Include="RestSharp" Version="106.6.9" />
<PackageReference Include="SevenZip" Version="19.0.0" /> <PackageReference Include="SevenZip" Version="19.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.4.0" /> <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.4.0" />
<PackageReference Include="taglib" Version="2.1.0" /> <PackageReference Include="taglib" Version="2.1.0" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Content Update="nlog.config" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project> </Project>
+33 -10
View File
@@ -3,23 +3,46 @@ using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore; using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NLog.Web;
namespace Icarus namespace Icarus
{ {
public class Program public class Program
{ {
public static void Main(string[] args) public static void Main(string[] args)
{ {
CreateWebHostBuilder(args).Build().Run(); var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => try
WebHost.CreateDefaultBuilder(args) {
.UseStartup<Startup>() logger.Debug("init main");
.UseUrls("http://localhost:5002"); CreateWebHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
logger.Error(ex, "An error occurred");
throw;
}
finally
{
NLog.LogManager.Shutdown();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls("http://localhost:5002")
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
})
.UseNLog() ;
} }
} }
+36 -32
View File
@@ -18,6 +18,9 @@ using Microsoft.EntityFrameworkCore;
using MySql.Data; using MySql.Data;
using MySql.Data.EntityFrameworkCore.Extensions; using MySql.Data.EntityFrameworkCore.Extensions;
using MySql.Data.MySqlClient; using MySql.Data.MySqlClient;
using NLog;
using NLog.Web;
using NLog.Web.AspNetCore;
using Icarus.Authorization; using Icarus.Authorization;
using Icarus.Authorization.Handlers; using Icarus.Authorization.Handlers;
@@ -25,18 +28,18 @@ using Icarus.Models.Context;
namespace Icarus namespace Icarus
{ {
public class Startup public class Startup
{ {
public Startup(IConfiguration configuration) public Startup(IConfiguration configuration)
{ {
Configuration = configuration; Configuration = configuration;
} }
public IConfiguration Configuration { get; } public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container. // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSingleton<IConfiguration>(Configuration); services.AddSingleton<IConfiguration>(Configuration);
@@ -80,34 +83,35 @@ namespace Icarus
var connString = Configuration.GetConnectionString("DefaultConnection"); var connString = Configuration.GetConnectionString("DefaultConnection");
services.Add(new ServiceDescriptor(typeof(MusicStoreContext), services.Add(new ServiceDescriptor(typeof(MusicStoreContext),
new MusicStoreContext(Configuration new MusicStoreContext(Configuration
.GetConnectionString("DefaultConnection")))); .GetConnectionString("DefaultConnection"))));
services.Add(new ServiceDescriptor(typeof(UserStoreContext), services.Add(new ServiceDescriptor(typeof(UserStoreContext),
new UserStoreContext(Configuration new UserStoreContext(Configuration
.GetConnectionString("DefaultConnection")))); .GetConnectionString("DefaultConnection"))));
services.AddDbContext<SongContext>(options => options.UseMySQL(connString)); services.AddDbContext<SongContext>(options => options.UseMySQL(connString));
services.AddDbContext<UserContext>(options => options.UseMySQL(connString)); services.AddDbContext<UserContext>(options => options.UseMySQL(connString));
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env) public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{ {
if (env.IsDevelopment()) if (env.IsDevelopment())
{ {
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
} }
else else
{ {
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts(); app.UseHsts();
} }
app.UseAuthentication(); app.UseAuthentication();
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseMvc(); app.UseMvc();
} }
} }
} }
+2 -1
View File
@@ -1,7 +1,8 @@
{ {
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Warning" "Default": "Trace",
"Microsoft": "Information"
} }
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
+33
View File
@@ -0,0 +1,33 @@
<?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="Icarus.txt">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="Icarus-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
<!-- another file log, only own logs. Uses some ASP.NET core renderers -->
<target xsi:type="File" name="ownFile-web" fileName="Icarus-${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 to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />
<!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" maxlevel="Info" final="true" /> <!-- BlackHole without writeTo -->
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>