示例:AspNetCore 2.2 MVC 注入日志

6 篇文章 0 订阅

一、目的:了解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("点击登录");

为写日志方法;

 

 

 

.Net Core2.1+NLog+数据库连接 <?xml version="1.0" encoding="utf-8" ?> <nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" throwExceptions="true" internalLogLevel="warn" internalLogFile="logfiles/internal-nlog.txt"> <targets> <target xsi:type="Null" name="blackhole" /> <target name="database" xsi:type="Database" dbProvider="System.Data.SqlClient" connectionString="Data Source=127.0.0.1;Initial Catalog=MiddleData;User ID=lzhu;Password=bl123456;" > <!-- create table NLog ( Id int identity, Application nvarchar(50) null, Logged datetime null, Level nvarchar(50) null, Message nvarchar(512) null, Logger nvarchar(250) null, Callsite nvarchar(512) null, Exception nvarchar(512) null, constraint PK_NLOG primary key (Id) ) --> <commandText> insert into nlog ( Application, Logged, Level, Message, Logger, CallSite, Exception ) values ( @Application, @Logged, @Level, @Message, @Logger, @Callsite, @Exception ); </commandText> <parameter name="@application" layout="NLogTestDemo" /> <parameter name="@logged" layout="${date}" /> <parameter name="@level" layout="${level}" /> <parameter name="@message" layout="${message}" /> <parameter name="@logger" layout="${logger}" /> <parameter name="@callSite" layout="${callsite:filename=true}" /> <parameter name="@exception" layout="${exception:tostring}" /> </target> </targets> <rules> <!--Skip Microsoft logs and so log only own logs--> <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" /> <logger name="NLogTestDemo.*" minlevel="Info" writeTo="database" /> </rules> </nlog>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值