Skip to content

Commit

Permalink
Add Serilog for Log Files
Browse files Browse the repository at this point in the history
  • Loading branch information
enkodellc committed Jun 5, 2019
1 parent 008d994 commit 366b529
Show file tree
Hide file tree
Showing 6 changed files with 159 additions and 14 deletions.
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,10 @@ will be depending on how much community support for it is.
This project is licensed under the terms of the [MIT license](LICENSE).

## News
### Blazor Boilerplate 0.1.0

### 0.1.1
- Updated Theme / Responsive
- Added Serilog Log Files

### 0.1.0
- Initial release
8 changes: 8 additions & 0 deletions src/BlazorBoilerplate.Server/BlazorBoilerplate.Server.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,19 @@
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0-preview5.19227.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0-preview5.19227.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.0.0-preview5.19227.1" />
<PackageReference Include="Serilog" Version="2.9.0-dev-01091" />
<PackageReference Include="Serilog.AspNetCore" Version="3.0.0-dev-00041" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.1.1-dev-00209" />
<PackageReference Include="Serilog.Sinks.File" Version="4.1.0-dev-00838" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\BlazorBoilerplate.Client\BlazorBoilerplate.Client.csproj" />
<ProjectReference Include="..\BlazorBoilerplate.Shared\BlazorBoilerplate.Shared.csproj" />
</ItemGroup>

<ItemGroup>
<Folder Include="Logs\" />
</ItemGroup>

</Project>
37 changes: 27 additions & 10 deletions src/BlazorBoilerplate.Server/Controllers/AuthorizeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,37 +7,52 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace BlazorBoilerplate.Server.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class AuthorizeController : ControllerBase
{
// Logger instance
ILogger<AuthorizeController> _logger;

private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;

public AuthorizeController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
public AuthorizeController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ILogger<AuthorizeController> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
}

[AllowAnonymous]
[HttpPost]
public async Task<IActionResult> Login(LoginParameters parameters)
{
if(!ModelState.IsValid) return BadRequest(ModelState.Values.SelectMany(state => state.Errors)
.Select(error => error.ErrorMessage)
.FirstOrDefault());
if (!ModelState.IsValid) return BadRequest(ModelState.Values.SelectMany(state => state.Errors)
.Select(error => error.ErrorMessage)
.FirstOrDefault());

var user = await _userManager.FindByNameAsync(parameters.UserName);
if (user == null) return BadRequest("User does not exist");
if (user == null)
{
_logger.LogInformation("User does not exist: {0}", parameters.UserName);
return BadRequest("User does not exist");
}

var singInResult = await _signInManager.CheckPasswordSignInAsync(user, parameters.Password, false);
if (!singInResult.Succeeded) return BadRequest("Invalid password");

await _signInManager.SignInAsync(user, parameters.RememberMe);
if (!singInResult.Succeeded)
{
_logger.LogInformation("Invalid password: {0}, {1}", parameters.UserName, parameters.Password);
return BadRequest("Invalid password");
}

_logger.LogInformation("Logged In: {0}, {1}", parameters.UserName, parameters.Password);
await _signInManager.SignInAsync(user, parameters.RememberMe);
return Ok(BuildUserInfo(user));
}

Expand All @@ -55,6 +70,8 @@ public async Task<IActionResult> Register(RegisterParameters parameters)
var result = await _userManager.CreateAsync(user, parameters.Password);
if (!result.Succeeded) return BadRequest(result.Errors.FirstOrDefault()?.Description);

_logger.LogInformation("New user registered: {0}", user);

return await Login(new LoginParameters
{
UserName = parameters.UserName,
Expand Down Expand Up @@ -100,7 +117,8 @@ public async Task<IActionResult> SendPasswordResetEmail(string emailAddress)
[HttpPost]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
_logger.LogInformation("User Logged out");
await _signInManager.SignOutAsync();
return Ok();
}

Expand All @@ -111,8 +129,7 @@ public async Task<UserInfo> UserInfo()
var user = await _userManager.GetUserAsync(HttpContext.User);
return BuildUserInfo(user);
}



private UserInfo BuildUserInfo(ApplicationUser user)
{
return new UserInfo
Expand Down
34 changes: 31 additions & 3 deletions src/BlazorBoilerplate.Server/Program.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,41 @@
using Microsoft.AspNetCore;
using System;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.File;
using Serilog.AspNetCore;
using Serilog.Settings.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.Hosting;

namespace BlazorBoilerplate.Server
{
public class Program
{
public static void Main(string[] args)
public static int Main(string[] args)
{
BuildWebHost(args).Run();
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings" + (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == Environments.Development ? ".Development.json" : ".json"))
.Build();

Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();

try
{
Log.Information("Starting web server host");
BuildWebHost(args).Run();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
return 1;
}
}

public static IWebHost BuildWebHost(string[] args) =>
Expand All @@ -17,6 +44,7 @@ public static IWebHost BuildWebHost(string[] args) =>
.AddCommandLine(args)
.Build())
.UseStartup<Startup>()
.UseSerilog()
.Build();
}
}
47 changes: 47 additions & 0 deletions src/BlazorBoilerplate.Server/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=blazorboilerplate;Trusted_Connection=True;MultipleActiveResultSets=true"
},

"ApplicationUrl": "http://localhost:53414/",

"SmtpConfig": {
"Host": "smtp.gmail.com",
"Port": 465,
"UseSSL": true,
"Name": "Blazor Boilerplate",
"Username": "[email protected]",
"EmailAddress": "[email protected]",
"Password": "xxxxx",
"ReplyToAddress": "[email protected]"
},
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs\\log-.log",
"rollingInterval": "Day",
"retainedFileCountLimit": 5
}
}
]
},
"AllowedHosts": "*"
}
40 changes: 40 additions & 0 deletions src/BlazorBoilerplate.Server/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=QuickAppPro;Trusted_Connection=True;MultipleActiveResultSets=true"
},

"ApplicationUrl": "http://demo.analyticbroker.com",

"SmtpConfig": {
"Host": "smtp.gmail.com",
"Port": 465,
"UseSSL": true,
"Name": "Blazor Boilerplate",
"Username": "[email protected]",
"EmailAddress": "[email protected]",
"Password": "xxxxx",
"ReplyToAddress": "[email protected]"
},

"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": {
"Default": "Warning",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs\\log-.log",
"rollingInterval": "Day",
"retainedFileCountLimit": 30
}
}
]
},
"AllowedHosts": "*"
}

0 comments on commit 366b529

Please sign in to comment.