Skip to content

Commit

Permalink
修改了日志输出的方式,使用 JSON 数据结构
Browse files Browse the repository at this point in the history
  • Loading branch information
Jijie Chen committed May 6, 2019
1 parent 6cc886e commit 8cca108
Show file tree
Hide file tree
Showing 11 changed files with 100 additions and 88 deletions.
10 changes: 6 additions & 4 deletions src/Discussion.Core/Logging/LoggerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,22 @@ namespace Discussion.Core.Logging
{
public static class LoggerExtensions
{
public static void LogModelState<T>(this ILogger<T> logger, string action, ModelStateDictionary modelState, string userName = null)
public static void LogModelState<T>(this ILogger<T> logger, string action, ModelStateDictionary modelState, int? userId = null, string userName = null)
{
var errorMessage = modelState.IsValid ? null : ApiResponse.Error(modelState).ErrorMessage;
var resultDesc = modelState.IsValid ? "格式正确" : "数据格式不正确";

var logLevel = modelState.IsValid ? LogLevel.Information : LogLevel.Warning;
logger.Log(logLevel, $"{action}{resultDesc}{userName}{errorMessage}");
logger.Log(logLevel, $"{action}{resultDesc}{{@Context}}", new {UserId = userId, UserName = userName, Result = errorMessage});
}

public static void LogIdentityResult<T>(this ILogger<T> logger, string action, IdentityResult result, string userName = null)
public static void LogIdentityResult<T>(this ILogger<T> logger, string action, IdentityResult result, int? userId = null, string userName = null)
{
var resultDesc = result.Succeeded ? "成功" : "失败";
var message = string.Join(";", result.Errors.Select(err => err.Description));

var logLevel = result.Succeeded ? LogLevel.Information : LogLevel.Warning;
logger.Log(logLevel, $"{action}{resultDesc}{userName}{message}");
logger.Log(logLevel, $"{action}{resultDesc}{{@Context}}", new { UserId = userId, UserName = userName, Result = message});
}
}
}
56 changes: 33 additions & 23 deletions src/Discussion.Web/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,11 @@ public async Task<IActionResult> DoSignin(

var logLevel = result.Succeeded ? LogLevel.Information : LogLevel.Warning;
var resultDesc = result.Succeeded ? "成功" : "失败";
_logger.Log(logLevel, $"用户登录{resultDesc}用户名 {viewModel.UserName}{result}");
_logger.Log(logLevel, $"用户登录{resultDesc}{{@LoginAttempt}}", new {viewModel.UserName, Result = result.ToString()} );
}
else
{
_logger.LogWarning($"用户登录失败:用户名 {viewModel.UserName}数据格式不正确");
_logger.LogWarning("用户登录失败:{@LoginAttempt}", new {viewModel.UserName, Result = "数据格式不正确"});
}

if (!result.Succeeded)
Expand Down Expand Up @@ -122,14 +122,14 @@ public async Task<IActionResult> DoRegister(UserViewModel registerModel)
{
if (!ModelState.IsValid)
{
_logger.LogInformation($"用户注册失败:用户名 {registerModel.UserName}数据格式不正确");
_logger.LogInformation("用户注册失败:{@RegisterAttempt}", new {registerModel.UserName, Result = "数据格式不正确"});
return View("Register");
}

if (!_settings.CanRegisterNewUsers())
{
const string errorMessage = "已关闭用户注册";
_logger.LogWarning($"用户注册失败:用户名 {registerModel.UserName}{errorMessage}");
_logger.LogWarning("用户注册失败:{@RegisterAttempt}", new {registerModel.UserName, Result = errorMessage});
ModelState.AddModelError("UserName", errorMessage);
return View("Register");
}
Expand All @@ -146,11 +146,11 @@ public async Task<IActionResult> DoRegister(UserViewModel registerModel)
{
var errorMessage = string.Join(";", result.Errors.Select(err => err.Description));
ModelState.AddModelError("UserName", errorMessage);
_logger.LogWarning($"用户注册失败:用户名 {registerModel.UserName}{errorMessage}");
_logger.LogWarning("用户注册失败:{@RegisterAttempt}", new {registerModel.UserName, Result = errorMessage});
return View("Register");
}

_logger.LogInformation($"用户注册成功:(UserId: {newUser.Id}, UserName: {newUser.UserName})");
_logger.LogInformation("用户注册成功:{@RegisterAttempt}", new {registerModel.UserName, UserId = newUser.Id});
await _signInManager.PasswordSignInAsync(
registerModel.UserName,
registerModel.Password,
Expand All @@ -176,20 +176,20 @@ public async Task<ApiResponse> DoForgotPassword(ForgotPasswordModel model)
{
if (!ModelState.IsValid)
{
_logger.LogWarning($"找回密码失败:用户名或邮箱 {model.UsernameOrEmail} 数据格式不正确");
_logger.LogWarning("发送重置密码邮件失败:{@ForgotPasswordAttempt}", new {model.UsernameOrEmail, Result = "数据格式不正确"});
return ApiResponse.Error(ModelState);
}

try
{
var user = GetUserBy(model);
await _userService.SendEmailRetrievePasswordAsync(user, Request.Scheme);
_logger.LogInformation($"发送重置密码邮件成功:{user.ConfirmedEmail}");
_logger.LogInformation("发送重置密码邮件成功:{ConfirmedEmail}", user.ConfirmedEmail);
return ApiResponse.NoContent();
}
catch (RetrievePasswordVerificationException e)
{
_logger.LogWarning($"找回密码失败:{model.UsernameOrEmail} {e.Message}");
_logger.LogWarning("发送重置密码邮件失败:{@ForgotPasswordAttempt}", new {model.UsernameOrEmail, Result = e.Message});
return ApiResponse.Error(e.Message);
}
}
Expand All @@ -200,42 +200,52 @@ public IActionResult ResetPassword(ResetPasswordModel model)
{
ModelState.Clear();

bool ret;
var userEmailToken = UserEmailToken.ExtractFromQueryString(model.Token);
if (userEmailToken == null)
{
ModelState.AddModelError(nameof(model.Token), "Token无法识别");
_logger.LogWarning($"重置密码失败:Token无法识别 {model.Token}");
return View(model);
var errorMessage = "无法识别的凭证";
ModelState.AddModelError(nameof(model.Token), errorMessage);
_logger.LogWarning("重置密码失败:{@ResetPasswordAttempt}", new {model.Token, model.UserId, Result = errorMessage});
return View("ResetPassword", model);
}

model.Token = userEmailToken.Token;
model.UserId = userEmailToken.UserId;

return View(model);
}

[HttpPost]
[Route("/reset-password")]
public async Task<IActionResult> DoResetPassword(ResetPasswordModel model)
{
if (!ModelState.IsValid) return View(model);
if (!ModelState.IsValid)
{
return View(model);
}

var user = await _userManager.FindByIdAsync(model.UserId.ToString());
if (user == null)
{
ModelState.AddModelError(nameof(model.UserId), "该用户不存在");
var errorMessage = "用户不存在";
ModelState.AddModelError(nameof(model.UserId), errorMessage);
_logger.LogWarning("重置密码失败:{@ResetPasswordAttempt}", new { model.Token, model.UserId, Result = errorMessage});
return View(model);
}

var result = await _userManager.ResetPasswordAsync(user, model.Token, model.Password);

if (result.Errors.Any())
result.Errors.ToList()
.ForEach(e => ModelState.AddModelError(e.Code, e.Description));

_logger.LogInformation($"重置密码成功:{user.UserName}");

model.Succeeded = true;
{
var msg = string.Join(";", result.Errors.Select(e => e.Description));
ModelState.AddModelError(nameof(model.Token), msg);
_logger.LogWarning("重置密码失败:{@ResetPasswordAttempt}", new { model.Token, model.UserId, Result = msg});
model.Succeeded = false;
}
else
{
_logger.LogInformation("重置密码成功:{UserName}", user.UserName);
model.Succeeded = true;
}

return View(model);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Discussion.Web/Controllers/CommonController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public async Task<ApiResponse> UploadFile(IFormFile file, string category)
? await storageFile.GetPublicUrlAsync(TimeSpan.MaxValue)
: Url.Action("DownloadFile", "Common", new { slug = fileRecord.Slug }, Request.Scheme);

_logger.LogInformation($"上传文件成功:{fileRecord.OriginalName}, {fileRecord.Size} bytes, {fileRecord.StoragePath}, (id: {fileRecord.Id})");
_logger.LogInformation("上传文件成功:{@UploadedFile}", new {fileRecord.OriginalName, fileRecord.Size, fileRecord.StoragePath, fileRecord.Id});
return ApiResponse.ActionResult(new
{
FileId = fileRecord.Id,
Expand Down
14 changes: 7 additions & 7 deletions src/Discussion.Web/Controllers/ReplyController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,27 +39,27 @@ public IActionResult Reply(int topicId, ReplyCreationModel replyCreationModel)

if (!_siteSettings.CanAddNewReplies())
{
var ex = new FeatureDisabledException();
_logger.LogWarning($"添加回复失败:{currentUser.UserName}{ex.Message}");
_logger.LogWarning("添加回复失败:{@ReplyAttempt}", new {currentUser.UserName, Result= new FeatureDisabledException().Message});
return BadRequest();
}

if (_siteSettings.RequireUserPhoneNumberVerified && !currentUser.PhoneNumberId.HasValue)
{
var ex = new UserVerificationRequiredException();
_logger.LogWarning($"添加回复失败:{currentUser.UserName}{ex.Message}");
_logger.LogWarning("添加回复失败:{@ReplyAttempt}", new {currentUser.UserName, Result = new UserVerificationRequiredException().Message});
return BadRequest();
}

var topic = _topicRepo.Get(topicId);
if (topic == null)
{
ModelState.AddModelError("TopicId", "话题不存在");
var errorMessage = "话题不存在";
_logger.LogWarning("添加回复失败:{@ReplyAttempt}", new {currentUser.UserName, Result = errorMessage});
ModelState.AddModelError("TopicId", errorMessage);
}

if (!ModelState.IsValid)
{
_logger.LogModelState("添加回复", ModelState, currentUser.UserName);
_logger.LogModelState("添加回复", ModelState, currentUser.Id, currentUser.UserName);
return BadRequest(ModelState);
}

Expand All @@ -77,7 +77,7 @@ public IActionResult Reply(int topicId, ReplyCreationModel replyCreationModel)
topic.ReplyCount += 1;
_topicRepo.Update(topic);

_logger.LogInformation($"添加回复成功:(TopicId: {topic.Id} ReplyId: {reply.Id} UserId: {currentUser.Id}, UserName: {currentUser.UserName})");
_logger.LogInformation("添加回复成功:{@ReplyAttempt}", new {TopicId = topic.Id, topic.ReplyCount, ReplyId = reply.Id, UserId = currentUser.Id, currentUser.UserName});
return NoContent();
}
}
Expand Down
18 changes: 6 additions & 12 deletions src/Discussion.Web/Controllers/TopicController.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Discussion.Web.ViewModels;
using Microsoft.AspNetCore.Authorization;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Discussion.Core.Data;
using Discussion.Core.Logging;
Expand All @@ -19,7 +14,6 @@
using Discussion.Web.Services.TopicManagement;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace Discussion.Web.Controllers
{
Expand Down Expand Up @@ -99,20 +93,20 @@ public ActionResult CreateTopic(TopicCreationModel model)
var userName = user.UserName;
if (!ModelState.IsValid)
{
_logger.LogModelState("创建话题", ModelState, userName);
_logger.LogModelState("创建话题", ModelState, user.Id, userName);
return BadRequest();
}

try
{
var topic = _topicService.CreateTopic(model);
_logger.LogInformation($"创建话题成功:{topic.Title} (TopicId: {topic.Id}, UserId: {user.Id}, UserName: {user.UserName})");
_logger.LogInformation("创建话题成功:{@NewTopicAttempt}", new {topic.Title, topic.Id, UserId = user.Id, user.UserName });
// ReSharper disable once Mvc.ActionNotResolved
return RedirectToAction("Index", new { topic.Id });
}
catch (InvalidOperationException ex)
{
_logger.LogWarning($"创建话题失败:(UserId: {user.Id}, UserName: {user.UserName}):{ex.Message}");
_logger.LogWarning("创建话题失败:{@NewTopicAttempt}", new { UserId = user.Id, user.UserName, Result = ex.Message });
return BadRequest();
}
}
Expand All @@ -126,7 +120,7 @@ public async Task<ActionResult> ImportFromWeChat(ChatHistoryImportingModel model
var weChatAccount = _wechatAccountRepo.All().FirstOrDefault(wxa => wxa.UserId == user.Id);
if (weChatAccount == null)
{
_logger.LogWarning($"无法导入对话,因为当前用户 (UserId: {user.Id}, UserName: {user.UserName}) 未绑定微信号");
_logger.LogWarning("导入对话失败:{@ImportAttempt}", new { UserId = user.Id, user.UserName, Result = "未绑定微信号" });
return BadRequest();
}

Expand Down Expand Up @@ -156,7 +150,7 @@ public async Task<ActionResult> ImportFromWeChat(ChatHistoryImportingModel model
topic.LastRepliedAt = replies.Last().CreatedAtUtc;
_topicRepo.Update(topic);

_logger.LogInformation($"导入对话成功:(TopicId: {topic.Id}, ChatId: {model.ChatId}, ReplyCount: {topic.ReplyCount}, UserId: {user.Id}, UserName: {user.UserName})");
_logger.LogInformation("导入对话成功:{@ImportAttempt}", new {TopicId = topic.Id, model.ChatId, topic.ReplyCount, UserId = user.Id, user.UserName});
return redirectResult;
}

Expand All @@ -168,7 +162,7 @@ public async Task<ApiResponse> GetWeChatSessionList()
var weChatAccount = _wechatAccountRepo.All().FirstOrDefault(wxa => wxa.UserId == user.Id);
if (weChatAccount == null)
{
_logger.LogWarning($"无法加载对话列表,因为当前用户 (UserId: {user.Id}, UserName: {user.UserName}) 未绑定微信号");
_logger.LogWarning("加载对话列表失败:{@ImportAttempt}", new { UserId = user.Id, user.UserName, Result = "未绑定微信号" });
return ApiResponse.NoContent(HttpStatusCode.BadRequest);
}

Expand Down
Loading

0 comments on commit 8cca108

Please sign in to comment.