Add logging to 'business' events

This commit is contained in:
ryanbrandenburg 2016-04-12 12:01:38 -07:00
parent 9818214c5c
commit 19325a6cce
8 changed files with 75 additions and 21 deletions

View File

@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MusicStore.Models; using MusicStore.Models;
namespace MusicStore.Controllers namespace MusicStore.Controllers
@ -15,12 +16,16 @@ namespace MusicStore.Controllers
[Authorize] [Authorize]
public class AccountController : Controller public class AccountController : Controller
{ {
private readonly ILogger<AccountController> _logger;
public AccountController( public AccountController(
UserManager<ApplicationUser> userManager, UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager) SignInManager<ApplicationUser> signInManager,
ILogger<AccountController> logger)
{ {
UserManager = userManager; UserManager = userManager;
SignInManager = signInManager; SignInManager = signInManager;
_logger = logger;
} }
public UserManager<ApplicationUser> UserManager { get; } public UserManager<ApplicationUser> UserManager { get; }
@ -53,6 +58,7 @@ namespace MusicStore.Controllers
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false); var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded) if (result.Succeeded)
{ {
_logger.LogInformation("Logged in {userName}.", model.Email);
return RedirectToLocal(returnUrl); return RedirectToLocal(returnUrl);
} }
if (result.RequiresTwoFactor) if (result.RequiresTwoFactor)
@ -65,6 +71,7 @@ namespace MusicStore.Controllers
} }
else else
{ {
_logger.LogWarning("Failed to log in {userName}.", model.Email);
ModelState.AddModelError("", "Invalid login attempt."); ModelState.AddModelError("", "Invalid login attempt.");
return View(model); return View(model);
} }
@ -145,6 +152,7 @@ namespace MusicStore.Controllers
var result = await UserManager.CreateAsync(user, model.Password); var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded) if (result.Succeeded)
{ {
_logger.LogInformation("User {userName} was created.", model.Email);
//Bug: Remember browser option missing? //Bug: Remember browser option missing?
//Uncomment this and comment the later part if account verification is not needed. //Uncomment this and comment the later part if account verification is not needed.
//await SignInManager.SignInAsync(user, isPersistent: false); //await SignInManager.SignInAsync(user, isPersistent: false);
@ -162,10 +170,10 @@ namespace MusicStore.Controllers
ViewBag.Link = callbackUrl; ViewBag.Link = callbackUrl;
return View("DemoLinkDisplay"); return View("DemoLinkDisplay");
#endif #endif
} }
AddErrors(result); AddErrors(result);
} }
// If we got this far, something failed, redisplay form // If we got this far, something failed, redisplay form
return View(model); return View(model);
} }
@ -443,6 +451,7 @@ namespace MusicStore.Controllers
[ValidateAntiForgeryToken] [ValidateAntiForgeryToken]
public async Task<ActionResult> LogOff() public async Task<ActionResult> LogOff()
{ {
var userName = HttpContext.User.Identity.Name;
// clear all items from the cart // clear all items from the cart
HttpContext.Session.Clear(); HttpContext.Session.Clear();
@ -459,6 +468,7 @@ namespace MusicStore.Controllers
}); });
} }
_logger.LogInformation("{userName} logged out.", userName);
return RedirectToAction("Index", "Home"); return RedirectToAction("Index", "Home");
} }
@ -477,6 +487,7 @@ namespace MusicStore.Controllers
foreach (var error in result.Errors) foreach (var error in result.Errors)
{ {
ModelState.AddModelError("", error.Description); ModelState.AddModelError("", error.Description);
_logger.LogWarning("Error in creating user: {error}", error.Description);
} }
} }

View File

@ -6,6 +6,7 @@ using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using MusicStore.Models; using MusicStore.Models;
namespace MusicStore.Controllers namespace MusicStore.Controllers
@ -15,6 +16,13 @@ namespace MusicStore.Controllers
{ {
private const string PromoCode = "FREE"; private const string PromoCode = "FREE";
private readonly ILogger<CheckoutController> _logger;
public CheckoutController(ILogger<CheckoutController> logger)
{
_logger = logger;
}
// //
// GET: /Checkout/ // GET: /Checkout/
public IActionResult AddressAndPayment() public IActionResult AddressAndPayment()
@ -58,6 +66,8 @@ namespace MusicStore.Controllers
var cart = ShoppingCart.GetCart(dbContext, HttpContext); var cart = ShoppingCart.GetCart(dbContext, HttpContext);
await cart.CreateOrder(order); await cart.CreateOrder(order);
_logger.LogInformation("User {userName} started checkout of {orderId}.", order.Username, order.OrderId);
// Save all changes // Save all changes
await dbContext.SaveChangesAsync(requestAborted); await dbContext.SaveChangesAsync(requestAborted);
@ -78,17 +88,24 @@ namespace MusicStore.Controllers
[FromServices] MusicStoreContext dbContext, [FromServices] MusicStoreContext dbContext,
int id) int id)
{ {
var userName = HttpContext.User.Identity.Name;
// Validate customer owns this order // Validate customer owns this order
bool isValid = await dbContext.Orders.AnyAsync( bool isValid = await dbContext.Orders.AnyAsync(
o => o.OrderId == id && o => o.OrderId == id &&
o.Username == HttpContext.User.Identity.Name); o.Username == userName);
if (isValid) if (isValid)
{ {
_logger.LogInformation("User {userName} completed checkout on order {orderId}.", userName, id);
return View(id); return View(id);
} }
else else
{ {
_logger.LogError(
"User {userName} tried to checkout with an order ({orderId}) that doesn't belong to them.",
userName,
id);
return View("Error"); return View("Error");
} }
} }

View File

@ -3,6 +3,7 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using MusicStore.Models; using MusicStore.Models;
using MusicStore.ViewModels; using MusicStore.ViewModels;
@ -10,9 +11,12 @@ namespace MusicStore.Controllers
{ {
public class ShoppingCartController : Controller public class ShoppingCartController : Controller
{ {
public ShoppingCartController(MusicStoreContext dbContext) private readonly ILogger<ShoppingCartController> _logger;
public ShoppingCartController(MusicStoreContext dbContext, ILogger<ShoppingCartController> logger)
{ {
DbContext = dbContext; DbContext = dbContext;
_logger = logger;
} }
public MusicStoreContext DbContext { get; } public MusicStoreContext DbContext { get; }
@ -49,6 +53,7 @@ namespace MusicStore.Controllers
cart.AddToCart(addedAlbum); cart.AddToCart(addedAlbum);
await DbContext.SaveChangesAsync(requestAborted); await DbContext.SaveChangesAsync(requestAborted);
_logger.LogInformation("Album {albumId} was added to the cart.", addedAlbum.AlbumId);
// Go back to the main store page for more shopping // Go back to the main store page for more shopping
return RedirectToAction("Index"); return RedirectToAction("Index");
@ -90,6 +95,8 @@ namespace MusicStore.Controllers
DeleteId = id DeleteId = id
}; };
_logger.LogInformation("Album {id} was removed from a cart.", id);
return Json(results); return Json(results);
} }
} }

View File

@ -4,6 +4,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.PlatformAbstractions; using Microsoft.Extensions.PlatformAbstractions;
using MusicStore.Components; using MusicStore.Components;
using MusicStore.Models; using MusicStore.Models;
@ -34,7 +35,6 @@ namespace MusicStore
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
services.Configure<AppSettings>(Configuration.GetSection("AppSettings")); services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
var useInMemoryStore = !_platform.IsRunningOnWindows var useInMemoryStore = !_platform.IsRunningOnWindows
|| _platform.IsRunningOnMono || _platform.IsRunningOnMono
|| _platform.IsRunningOnNanoServer; || _platform.IsRunningOnNanoServer;
@ -48,7 +48,7 @@ namespace MusicStore
else else
{ {
services.AddDbContext<MusicStoreContext>(options => services.AddDbContext<MusicStoreContext>(options =>
options.UseSqlServer(Configuration[StoreConfig.ConnectionStringKey.Replace("__",":")])); options.UseSqlServer(Configuration[StoreConfig.ConnectionStringKey.Replace("__", ":")]));
} }
// Add Identity services to the services container // Add Identity services to the services container
@ -68,6 +68,8 @@ namespace MusicStore
}); });
}); });
services.AddLogging();
// Add MVC services to the services container // Add MVC services to the services container
services.AddMvc(); services.AddMvc();
@ -86,7 +88,8 @@ namespace MusicStore
{ {
options.AddPolicy( options.AddPolicy(
"ManageStore", "ManageStore",
authBuilder => { authBuilder =>
{
authBuilder.RequireClaim("ManageStore", "Allowed"); authBuilder.RequireClaim("ManageStore", "Allowed");
}); });
}); });

View File

@ -13,6 +13,9 @@
], ],
"preserveCompilationContext": true "preserveCompilationContext": true
}, },
"commands": {
"web": "MusicStore"
},
"compile": [ "compile": [
"../../shared/**/*.cs" "../../shared/**/*.cs"
], ],
@ -50,7 +53,7 @@
"Microsoft.NETCore.Platforms": "1.0.1-*", "Microsoft.NETCore.Platforms": "1.0.1-*",
}, },
"frameworks": { "frameworks": {
"net451": {}, "net451": { },
"netstandardapp1.5": { "netstandardapp1.5": {
"dependencies": { "dependencies": {
"NETStandard.Library": "1.5.0-*" "NETStandard.Library": "1.5.0-*"

View File

@ -6,12 +6,13 @@
"../../shared/**/*.cs" "../../shared/**/*.cs"
], ],
"dependencies": { "dependencies": {
"Microsoft.AspNetCore.Identity": "1.0.0-*",
"Microsoft.AspNetCore.Authentication.Cookies": "1.0.0-*", "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0-*",
"Microsoft.AspNetCore.Authentication.OpenIdConnect": "0.1.0-*", "Microsoft.AspNetCore.Authentication.OpenIdConnect": "0.1.0-*",
"Microsoft.AspNetCore.Identity": "1.0.0-*",
"Microsoft.AspNetCore.Server.Testing": "1.0.0-*", "Microsoft.AspNetCore.Server.Testing": "1.0.0-*",
"Microsoft.AspNetCore.WebUtilities": "1.0.0-*", "Microsoft.AspNetCore.WebUtilities": "1.0.0-*",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-*", "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-*",
"Microsoft.Extensions.Logging": "1.0.0-*",
"Microsoft.Extensions.Logging.Console": "1.0.0-*", "Microsoft.Extensions.Logging.Console": "1.0.0-*",
"xunit": "2.1.0" "xunit": "2.1.0"
}, },

View File

@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives; using Microsoft.Extensions.Primitives;
using MusicStore.Models; using MusicStore.Models;
using Xunit; using Xunit;
@ -33,7 +34,7 @@ namespace MusicStore.Controllers
public void AddressAndPayment_ReturnsDefaultView() public void AddressAndPayment_ReturnsDefaultView()
{ {
// Arrange // Arrange
var controller = new CheckoutController(); var controller = new CheckoutController(_serviceProvider.GetService<ILogger<CheckoutController>>());
// Act // Act
var result = controller.AddressAndPayment(); var result = controller.AddressAndPayment();
@ -81,7 +82,7 @@ namespace MusicStore.Controllers
dbContext.AddRange(cartItems); dbContext.AddRange(cartItems);
dbContext.SaveChanges(); dbContext.SaveChanges();
var controller = new CheckoutController(); var controller = new CheckoutController(_serviceProvider.GetService<ILogger<CheckoutController>>());
controller.ControllerContext.HttpContext = httpContext; controller.ControllerContext.HttpContext = httpContext;
// Act // Act
@ -107,7 +108,7 @@ namespace MusicStore.Controllers
context.Request.Form = context.Request.Form =
new FormCollection(new Dictionary<string, StringValues>()); new FormCollection(new Dictionary<string, StringValues>());
var controller = new CheckoutController(); var controller = new CheckoutController(_serviceProvider.GetService<ILogger<CheckoutController>>());
controller.ControllerContext.HttpContext = context; controller.ControllerContext.HttpContext = context;
// Do not need actual data for Order; the Order object will be checked for the reference equality. // Do not need actual data for Order; the Order object will be checked for the reference equality.
@ -133,7 +134,7 @@ namespace MusicStore.Controllers
new FormCollection(new Dictionary<string, StringValues>()); new FormCollection(new Dictionary<string, StringValues>());
var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>(); var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();
var controller = new CheckoutController(); var controller = new CheckoutController(_serviceProvider.GetService<ILogger<CheckoutController>>());
controller.ControllerContext.HttpContext = context; controller.ControllerContext.HttpContext = context;
var order = new Order(); var order = new Order();
@ -153,7 +154,7 @@ namespace MusicStore.Controllers
public async Task AddressAndPayment_ReturnsOrderIfInvalidOrderModel() public async Task AddressAndPayment_ReturnsOrderIfInvalidOrderModel()
{ {
// Arrange // Arrange
var controller = new CheckoutController(); var controller = new CheckoutController(_serviceProvider.GetService<ILogger<CheckoutController>>());
controller.ModelState.AddModelError("a", "ModelErrorA"); controller.ModelState.AddModelError("a", "ModelErrorA");
var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>(); var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();
@ -192,7 +193,7 @@ namespace MusicStore.Controllers
}); });
dbContext.SaveChanges(); dbContext.SaveChanges();
var controller = new CheckoutController(); var controller = new CheckoutController(_serviceProvider.GetService<ILogger<CheckoutController>>());
controller.ControllerContext.HttpContext = httpContext; controller.ControllerContext.HttpContext = httpContext;
// Act // Act
@ -214,7 +215,7 @@ namespace MusicStore.Controllers
var dbContext = var dbContext =
_serviceProvider.GetRequiredService<MusicStoreContext>(); _serviceProvider.GetRequiredService<MusicStoreContext>();
var controller = new CheckoutController(); var controller = new CheckoutController(_serviceProvider.GetService<ILogger<CheckoutController>>());
controller.ControllerContext.HttpContext = new DefaultHttpContext(); controller.ControllerContext.HttpContext = new DefaultHttpContext();
// Act // Act

View File

@ -9,6 +9,7 @@ using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ObjectPool; using Microsoft.Extensions.ObjectPool;
using Microsoft.Extensions.Primitives; using Microsoft.Extensions.Primitives;
using MusicStore.Models; using MusicStore.Models;
@ -42,7 +43,9 @@ namespace MusicStore.Controllers
var httpContext = new DefaultHttpContext(); var httpContext = new DefaultHttpContext();
httpContext.Session = new TestSession(); httpContext.Session = new TestSession();
var controller = new ShoppingCartController(_serviceProvider.GetRequiredService<MusicStoreContext>()); var controller = new ShoppingCartController(
_serviceProvider.GetRequiredService<MusicStoreContext>(),
_serviceProvider.GetService<ILogger<ShoppingCartController>>());
controller.ControllerContext.HttpContext = httpContext; controller.ControllerContext.HttpContext = httpContext;
// Act // Act
@ -66,7 +69,9 @@ namespace MusicStore.Controllers
httpContext.Session = new TestSession(); httpContext.Session = new TestSession();
httpContext.Session.SetString("Session", "CartId_A"); httpContext.Session.SetString("Session", "CartId_A");
var controller = new ShoppingCartController(_serviceProvider.GetRequiredService<MusicStoreContext>()); var controller = new ShoppingCartController(
_serviceProvider.GetRequiredService<MusicStoreContext>(),
_serviceProvider.GetService<ILogger<ShoppingCartController>>());
controller.ControllerContext.HttpContext = httpContext; controller.ControllerContext.HttpContext = httpContext;
// Act // Act
@ -100,7 +105,9 @@ namespace MusicStore.Controllers
dbContext.AddRange(cartItems); dbContext.AddRange(cartItems);
dbContext.SaveChanges(); dbContext.SaveChanges();
var controller = new ShoppingCartController(dbContext); var controller = new ShoppingCartController(
dbContext,
_serviceProvider.GetService<ILogger<ShoppingCartController>>());
controller.ControllerContext.HttpContext = httpContext; controller.ControllerContext.HttpContext = httpContext;
// Act // Act
@ -131,7 +138,9 @@ namespace MusicStore.Controllers
dbContext.AddRange(albums); dbContext.AddRange(albums);
dbContext.SaveChanges(); dbContext.SaveChanges();
var controller = new ShoppingCartController(dbContext); var controller = new ShoppingCartController(
dbContext,
_serviceProvider.GetService<ILogger<ShoppingCartController>>());
controller.ControllerContext.HttpContext = httpContext; controller.ControllerContext.HttpContext = httpContext;
// Act // Act
@ -184,7 +193,9 @@ namespace MusicStore.Controllers
httpContext.Request.Headers.Add(headers); httpContext.Request.Headers.Add(headers);
// Cotroller initialization // Cotroller initialization
var controller = new ShoppingCartController(dbContext); var controller = new ShoppingCartController(
dbContext,
_serviceProvider.GetService<ILogger<ShoppingCartController>>());
controller.ControllerContext.HttpContext = httpContext; controller.ControllerContext.HttpContext = httpContext;
// Act // Act