一、目的:了解Asp.net Core MVC中添加日志模块的过程
二、过程:
1、添加Logging.json到应用程序集中
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
},
"Console":
{
"IncludeScopes": "true",
"TimestampFormat": "[HH:mm:ss] ",
"LogToStandardErrorThreshold": "Warning"
}
}
2、在Startup中代码如下
public class Startup
{
ILogger _logger;
public Startup(IConfiguration configuration, ILogger<Startup> logger)
{
Configuration = configuration;
_logger = logger;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
_logger.LogInformation("Step ConfigureServices");
// Do:获取数据库连接字符串
string cs = this.Configuration.GetConnectionString("MySqlConnection");
// Do:注册数据上下文
services.AddDbContextWithConnectString<DataContext>(cs);
// Do:依赖注入
services.AddScoped<IUserAccountRespositroy, UserAccountRespositroy>();
// Message:注册内服务领域模型
//services.AddScoped<TestService>();
//services.AddTransient(l => new HomeControler(new TestServer("fdfdd")));
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// Message:注册过滤器
//services.AddMvc(l=>l.Filters.Add(new SamepleGlobalActionFilter())) ;
// Do:注册日志
var loggingConfiguration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("logging.json", optional: false, reloadOnChange: true)
.Build();
services.AddLogging(builder =>
{
builder
.AddConfiguration(loggingConfiguration.GetSection("Logging"))
.AddFilter("Microsoft", LogLevel.Warning)
.AddFilter("HeBianGu.Product.WebApp.Demo", LogLevel.Debug)
.AddConsole();
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Do:注册日志
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// 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.UseHttpsRedirection();
app.UseStaticFiles();
//app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Login}/{id?}");
});
//app.UseMvc(routes =>
//{
// routes.MapRoute(
// name: "default",
// template: "{controller=User}/{action=Index}/{id?}");
//});
}
}
其中,
// Do:注册日志
var loggingConfiguration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("logging.json", optional: false, reloadOnChange: true)
.Build();
services.AddLogging(builder =>
{
builder
.AddConfiguration(loggingConfiguration.GetSection("Logging"))
.AddFilter("Microsoft", LogLevel.Warning)
.AddFilter("HeBianGu.Product.WebApp.Demo", LogLevel.Debug)
.AddConsole();
});
部分为注册日志的代码
3、在Controler中应用注入日志
public class HomeController : Controller
{
IUserAccountRespositroy _respository;
ILogger _logger;
public HomeController(IUserAccountRespositroy respository, ILogger<HomeController> logger)
{
_respository = respository;
_logger = logger;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
public IActionResult Login()
{
return View();
}
[HttpPost]
public IActionResult Login(LoginViewModel model)
{
_logger.LogInformation("点击登录");
if (ModelState.IsValid)
{
//检查用户信息
var user = _respository.CheckUserLogin(model.UserName, model.Password);
if (user != null)
{
//记录Session
//HttpContext.Session.SetString("CurrentUserId", user.Id.ToString());
//HttpContext.Session.Set("CurrentUser", ByteConvertHelper.Object2Bytes(user));
//跳转到系统首页
return RedirectToAction("Monitor", "Monitor");
}
ViewBag.ErrorInfo = "用户名或密码错误。";
return View();
}
foreach (var item in ModelState.Values)
{
if (item.Errors.Count > 0)
{
ViewBag.ErrorInfo = item.Errors[0].ErrorMessage;
break;
}
}
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
// Message:每个控制器的基类Controler 都包含两个过滤器,这个在过滤器之后调用,下面在过滤器之前调用
public override void OnActionExecuted(ActionExecutedContext context)
{
Debug.WriteLine("OnActionExecuted");
base.OnActionExecuted(context);
}
public override void OnActionExecuting(ActionExecutingContext context)
{
Debug.WriteLine("OnActionExecuting");
base.OnActionExecuting(context);
}
}
其中,
ILogger _logger;
public HomeController(IUserAccountRespositroy respository, ILogger<HomeController> logger)
{
_respository = respository;
_logger = logger;
}
部分为获取日志方法;
_logger.LogInformation("点击登录");
为写日志方法;