代码之家  ›  专栏  ›  技术社区  ›  Patrick

即使此时我没有实现日志语句,控制台输出中的错误日志从何而来?

  •  0
  • Patrick  · 技术社区  · 2 年前

    builder.Host.UseSerilog() 然后使用 Microsoft.Extensions.Logging.ILogger<out TCategoryName>

    namespace ConsoleApp1;
    
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
            throw new InvalidOperationException("Hello, World as error");
        }
    }
    

    以下输出来自哪里?有没有办法在没有 try catch 并在任何可能的错误发生时手动记录?

    Unhandled exception. System.InvalidOperationException: Hello, World as error
       at ConsoleApp1.Program.Main(String[] args) in C:\Users\Admin\source\repos\ConsoleApp1\ConsoleApp1\Program.cs:line 8
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   gunr2171    2 年前

    以下输出来自哪里?

    您的程序中有一个未处理的异常。这意味着您允许异常冒泡并从应用程序中溢出,因此dotnet运行时被迫为您处理它。

    就像 Console.WriteLine()

    我真的建议使用try/catch,这就是它的设计目的。它让你有时间思考应用程序的设计,并允许你在处理应用程序时执行所有自定义逻辑 非常精确的错误 .

    John Wu AppDomain.UnhandledException Event 然而,这或多或少相当于“对整个应用程序进行一次尝试/捕获,然后到此为止”。

    文档示例如下:

    using System;
    
    public class Example
    {
       public static void Main()
       {
          AppDomain currentDomain = AppDomain.CurrentDomain;
          currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
    
          try {
             throw new Exception("1");
          } catch (Exception e) {
             Console.WriteLine("Catch clause caught : {0} \n", e.Message);
          }
    
          throw new Exception("2");
       }
    
       static void MyHandler(object sender, UnhandledExceptionEventArgs args)
       {
          Exception e = (Exception) args.ExceptionObject;
          Console.WriteLine("MyHandler caught : " + e.Message);
          Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
       }
    }
    // The example displays the following output:
    //       Catch clause caught : 1
    //
    //       MyHandler caught : 2
    //       Runtime terminating: True
    //
    //       Unhandled Exception: System.Exception: 2
    //          at Example.Main()