当前位置: 首页>>代码示例>>C#>>正文


C# LoggerConfiguration.Error方法代码示例

本文整理汇总了C#中Serilog.LoggerConfiguration.Error方法的典型用法代码示例。如果您正苦于以下问题:C# LoggerConfiguration.Error方法的具体用法?C# LoggerConfiguration.Error怎么用?C# LoggerConfiguration.Error使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Serilog.LoggerConfiguration的用法示例。


在下文中一共展示了LoggerConfiguration.Error方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Application_Error

        void Application_Error(object sender, EventArgs e)
        {
            var exception = Server.GetLastError();

            // Log the exception.
            using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger())
            {
                if (HttpContext.Current != null)
                    log.Error(exception, "Application_Error: an exception occurred at {0}", HttpContext.Current.Request.Url.ToString());
                else
                    log.Error(exception, "Application_Error: an exception occurred (but HttpContext.Current is null so the URL was not captured)");
            }
        }
开发者ID:txsll,项目名称:SLLInvoices,代码行数:13,代码来源:Global.asax.cs

示例2: Run

 public static void Run()
 {
     var logger = new LoggerConfiguration()
     .WriteTo.MSSqlServer(@"Server=.;Database=LogEvents;Trusted_Connection=True;", "Logs")
     .CreateLogger();
     logger.Information("I am an information log");
     logger.Error("Hello, I am an error log");
 }
开发者ID:andyfengc,项目名称:SerilogTutorial,代码行数:8,代码来源:DatabaseLogger.cs

示例3: Log

        public override void Log(ExceptionLoggerContext context)
        {
            using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger())
            {
                log.Error(context.Exception, "CustomExceptionLogger: An exception occurred in an API controller; see the log entry below for the request");
            }

            base.Log(context);
        }
开发者ID:txsll,项目名称:SLLInvoices,代码行数:9,代码来源:CustomExceptionLogger.cs

示例4: Run

 public static void Run()
 {
     var logger = new LoggerConfiguration()
         .WriteTo.ColoredConsole()
         .WriteTo.RollingFile(@"D:\Log-{Date}.txt")
         .CreateLogger();
     var appointment =
         new { Id = 1, Subject = "Meeting of database migration", Timestamp = new DateTime(2015, 3, 12) };
     logger.Information("An appointment is booked successfully: {@appountment}", appointment);
     logger.Error("Failed to book an appointment: {@appountment}", appointment);
 }
开发者ID:andyfengc,项目名称:SerilogTutorial,代码行数:11,代码来源:BasicLogger.cs

示例5: Main

        static void Main(string[] args)
        {
            var logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.ColoredConsole()
                .WriteTo.Elasticsearch("http://localhost:9200")
                .CreateLogger();

            logger.Information("Here is an informational message");
            logger.Debug("Some debug level info");
            logger.Error("And error level info");
        }
开发者ID:PyroJoke,项目名称:LogPatterns,代码行数:12,代码来源:Program.cs

示例6: SetLevel

 public static void SetLevel()
 {
     var logger = new LoggerConfiguration()
      .MinimumLevel.Debug()
      .WriteTo.ColoredConsole()
      .CreateLogger();
     var appointment =
         new { Id = 1, Subject = "Meeting of database migration", Timestamp = new DateTime(2015, 3, 12) };
     logger.Verbose("You will not see this log");
     logger.Information("An appointment is booked successfully: {@appountment}", appointment);
     logger.Error("Failed to book an appointment: {@appountment}", appointment);
 }
开发者ID:andyfengc,项目名称:SerilogTutorial,代码行数:12,代码来源:CustomizedLogger.cs

示例7: OnActionExecuting

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ModelState.IsValid == false)
            {
                // Log the error.
                using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger())
                {
                    log.Error("The ValidateApiModel attribute caught a model validation error for user {0} with the following HTTP request: {1}",
                        actionContext.RequestContext.Principal.Identity.Name,
                        actionContext.Request);
                }

                // Send a 400 Bad Request response along with the model state.
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
            }
        }
开发者ID:txsll,项目名称:SLLInvoices,代码行数:16,代码来源:ValidateApiModelAttribute.cs

示例8: EditFile

 public ActionResult EditFile(string editedText)
 {
     try
     {
         using (StreamWriter writer = new StreamWriter(Path.Combine(directory, "AboutPageText.txt")))
         {
             writer.Write(editedText);
         }
     }
     catch (System.Exception ex)
     {
         var logger = new LoggerConfiguration().WriteTo.File(@"C:\Users\Nour\Downloads\myapplog.txt", Serilog.Events.LogEventLevel.Error).CreateLogger();
         logger.Error(ex.Message, "cannot write file");
     }
     return View("Index");
 }
开发者ID:n-alomary,项目名称:GameTrader,代码行数:16,代码来源:AdminController.cs

示例9: About

 public ActionResult About()
 {
     try
     {
         using (StreamReader reader = new StreamReader(@"C:\Users\Nour\Downloads\AboutPageText.txt"))
         {
             ViewBag.Message = reader.ReadToEnd();
         }
     }
     catch (Exception ex)
     {
         var logger = new LoggerConfiguration().WriteTo.File(@"C:\Users\Nour\Downloads\myapplog.txt", Serilog.Events.LogEventLevel.Error).CreateLogger();
         logger.Error(ex.Message, "This is possibly because file cannot be found.");
         ViewBag.Message = null;
     }
     return View();
 }
开发者ID:n-alomary,项目名称:GameTrader,代码行数:17,代码来源:HomeController.cs

示例10: Main

        static void Main(string[] args)
        {

            //Configuration by AppSettings
            var logger = new LoggerConfiguration()
                .ReadFrom.AppSettings()
                .MinimumLevel.Debug()
                .Enrich.WithThreadId()
                .Enrich.WithProperty("MyMetaProperty", "Oh! the beautiful value!")
                .WriteTo.ColoredConsole()
                .CreateLogger();

            ////Configuration by code
            //var logger = new LoggerConfiguration()
            //    .MinimumLevel.Debug()
            //    .Enrich.WithThreadId()
            //    .Enrich.WithProperty("MyMetaProperty", "Oh! the beautiful value!")
            //    .WriteTo.ColoredConsole()
            //    .WriteTo.BrowserConsole(port: 9999, buffer: 50)
            //    .CreateLogger();

            OpenBrowserToBrowserLogUrl();

            logger.Information("Hello!");
            Thread.Sleep(1000);
            for (int i = 0; i < 100000; i++)
            {
                logger.Information("Hello this is a log from a server-side process!");
                Thread.Sleep(100);
                logger.Warning("Hello this is a warning from a server-side process!");
                logger.Debug("... and here is another log again ({IndexLoop})", i);
                Thread.Sleep(200);
                try
                {
                    ThrowExceptionWithStackTrace(4);
                }
                catch (Exception ex)
                {
                    logger.Error(ex, "An error has occured, really?");
                }

                Thread.Sleep(1000);
            }
        }
开发者ID:pmiossec,项目名称:BrowserLog,代码行数:44,代码来源:Program.cs

示例11: Handle

        public override void Handle(ExceptionHandlerContext context)
        {
            using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger())
            {
                log.Error(context.Exception, "CustomApiExceptionHandler: An API exception occurred and a 500 Internal Server Error was returned");
                log.Information("CustomApiExceptionHandler: The request that caused the exception above was {0}", context.Request);
            }

            string message;

            if (context.Exception is Domain.Services.BusinessLogicException)
            {
                message = "The database update you requested cannot be made because it violates business logic rules — " + context.Exception.Message;
            }
            else if (context.Exception is System.Data.Entity.Infrastructure.DbUpdateException)
            {
                message = "An error occurred while trying to update the database.";

                if (context.Exception.InnerException != null)
                {
                    message += " " + context.Exception.InnerException.Message.Replace(" See the inner exception for details.", string.Empty);
                    if (context.Exception.InnerException.InnerException != null)
                        message += " " + context.Exception.InnerException.InnerException.Message + ".";
                }

                context.Result = new InternalServerErrorWithCustomMessageResult(message);
            }
            else
            {
                message = context.Exception.Message;
            }

            // Return a 500 Server Error with a message.
            context.Result = new InternalServerErrorWithCustomMessageResult(message);

            base.Handle(context);
        }
开发者ID:txsll,项目名称:SLLInvoices,代码行数:37,代码来源:CustomApiExceptionHandler.cs

示例12: OnException

        // This creates a CustomHandleError attribute to be used in MVC controllers.
        // It is modeled after the code at https://stackoverflow.com/questions/23779991/can-web-config-httperrors-section-and-a-webapi-area-coexist.
        // If we are handling an exception and it is of type HttpException, keep the current URL and show the Error.cshtml view.
        // Create a TempDataDictionary and send it to the Error view for processing.
        // This is intended to catch all 500 errors.
        // Without it, some parts of MVC would let IIS handle the error, which bypasses the custom error page.
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.Exception != null && (filterContext.Exception is HttpException || filterContext.Exception is Domain.Services.BusinessLogicException))
            {
                string modelErrors = "<br>";

                foreach (ModelState modelState in filterContext.Controller.ViewData.ModelState.Values)
                    foreach (ModelError error in modelState.Errors)
                        modelErrors += error.ErrorMessage + "<br>";
                if (modelErrors.Length >= 4)
                    modelErrors = modelErrors.Substring(0, modelErrors.Length - 4);

                // Log the exception.
                using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger())
                {
                    string msg = "CustomHandleError: ";

                    if (filterContext.Exception is HttpException)
                        msg += "an HttpException occurred";
                    else if (filterContext.Exception is Domain.Services.BusinessLogicException)
                        msg += "a BusinessLogicException occurred";

                    log.Error(filterContext.Exception, msg);

                    if (!string.IsNullOrWhiteSpace(modelErrors))
                        log.Error("There were model errors: {0}", modelErrors.Replace("<br>", "; "));
                }

                TempDataDictionary tempData = new TempDataDictionary();
                tempData["ErrorMessage"] = filterContext.Exception.Message;

                if (!string.IsNullOrWhiteSpace(modelErrors))
                    tempData["ErrorMessage"] += modelErrors;

                int httpCode = (int) HttpStatusCode.InternalServerError;
                if (filterContext.Exception is HttpException)
                {
                    HttpException myException = ((HttpException) filterContext.Exception);
                    httpCode = myException.GetHttpCode();
                    tempData["HttpCode"] = httpCode;
                }
                if (filterContext.Exception is Domain.Services.BusinessLogicException)
                {
                    tempData["HttpCode"] = (int) HttpStatusCode.Forbidden;
                    httpCode = (int) HttpStatusCode.Forbidden;
                }

                filterContext.Result = new ViewResult { ViewName = "Error", TempData = tempData };
                filterContext.HttpContext.Response.StatusCode = httpCode;
                filterContext.HttpContext.Response.StatusDescription = filterContext.Exception.Message;
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            }
            else
            {
                // Log the exception.
                using (var log = new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger())
                {
                    log.Error(filterContext.Exception, "CustomHandleError: an unhandled exception occurred");
                }

                base.OnException(filterContext);
            }
        }
开发者ID:txsll,项目名称:SLLInvoices,代码行数:70,代码来源:CustomHandleError.cs


注:本文中的Serilog.LoggerConfiguration.Error方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。