|
|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
在C#开发过程中,输出信息显示是开发者与程序交互的重要方式。无论是简单的控制台应用程序还是复杂的企业级系统,有效地输出和显示信息都是调试、监控和维护程序的关键环节。本文将全面介绍C#中从基础的Console.WriteLine到高级的Debug调试技巧,帮助开发者掌握各种输出窗口信息显示的方法,提高开发效率和程序调试能力。
基础输出方法:Console.WriteLine及其相关方法
Console.WriteLine基础用法
Console.WriteLine是C#中最基本也是最常用的输出方法,它将指定的文本或数据输出到控制台窗口,并在末尾添加一个换行符。
- // 输出简单文本
- Console.WriteLine("Hello, World!");
- // 输出变量的值
- int number = 42;
- Console.WriteLine(number);
- // 使用格式化字符串输出
- string name = "Alice";
- int age = 30;
- Console.WriteLine("Name: {0}, Age: {1}", name, age);
- // 使用字符串插值(C# 6.0及以上版本)
- Console.WriteLine($"Name: {name}, Age: {age}");
复制代码
Console.Write方法
与Console.WriteLine不同,Console.Write方法在输出后不添加换行符。
- Console.Write("This is on the same line. ");
- Console.Write("This continues the same line.");
- // 输出: This is on the same line. This continues the same line.
复制代码
格式化输出
C#提供了多种格式化输出的方式,使开发者能够控制数据的显示格式。
- // 数值格式化
- double price = 19.99;
- Console.WriteLine("Price: {0:C}", price); // 货币格式
- Console.WriteLine("Price: {0:F2}", price); // 固定小数点格式
- Console.WriteLine("Percentage: {0:P}", 0.25); // 百分比格式
- // 日期格式化
- DateTime now = DateTime.Now;
- Console.WriteLine("Date: {0:d}", now); // 短日期格式
- Console.WriteLine("Date: {0:D}", now); // 长日期格式
- Console.WriteLine("Time: {0:t}", now); // 短时间格式
- Console.WriteLine("Time: {0:T}", now); // 长时间格式
复制代码
控制台颜色设置
开发者可以通过设置控制台的前景色和背景色来增强输出的可读性。
- // 保存当前颜色
- ConsoleColor originalForegroundColor = Console.ForegroundColor;
- ConsoleColor originalBackgroundColor = Console.BackgroundColor;
- // 设置新的颜色
- Console.ForegroundColor = ConsoleColor.Yellow;
- Console.BackgroundColor = ConsoleColor.Blue;
- // 输出彩色文本
- Console.WriteLine("This is a colored message.");
- // 恢复原始颜色
- Console.ForegroundColor = originalForegroundColor;
- Console.BackgroundColor = originalBackgroundColor;
复制代码
控制台窗口操作
C#还提供了操作控制台窗口的方法,如设置窗口大小、标题等。
- // 设置窗口标题
- Console.Title = "My Console Application";
- // 设置窗口大小
- Console.WindowWidth = 100;
- Console.WindowHeight = 40;
- // 清除控制台窗口
- Console.Clear();
- // 获取光标位置并设置
- int left = Console.CursorLeft;
- int top = Console.CursorTop;
- Console.SetCursorPosition(10, 5);
- Console.WriteLine("Positioned text");
- Console.SetCursorPosition(left, top);
复制代码
Console.ReadLine和Console.ReadKey
除了输出方法,Console类还提供了读取用户输入的方法。
- // 读取一行文本
- Console.WriteLine("Please enter your name:");
- string name = Console.ReadLine();
- Console.WriteLine($"Hello, {name}!");
- // 读取单个按键
- Console.WriteLine("Press any key to continue...");
- ConsoleKeyInfo keyInfo = Console.ReadKey();
- Console.WriteLine($"\nYou pressed: {keyInfo.Key}");
复制代码
调试输出:Debug类和Trace类的使用
Debug类基础用法
System.Diagnostics.Debug类提供了一组方法,用于在调试过程中输出信息。这些输出只在调试模式下可见,在发布版本中会被自动忽略。
- using System.Diagnostics;
- // 基本Debug输出
- Debug.WriteLine("This is a debug message");
- // 条件Debug输出
- bool debugMode = true;
- Debug.WriteLineIf(debugMode, "Debug mode is active");
- // 断言
- int value = 5;
- Debug.Assert(value > 10, "Value should be greater than 10");
复制代码
Trace类基础用法
System.Diagnostics.Trace类与Debug类类似,但它的输出在调试和发布版本中都会保留。
- using System.Diagnostics;
- // 基本Trace输出
- Trace.WriteLine("This is a trace message");
- // 条件Trace输出
- bool traceEnabled = true;
- Trace.WriteLineIf(traceEnabled, "Trace is enabled");
- // 警告和错误信息
- Trace.TraceWarning("This is a warning");
- Trace.TraceError("This is an error");
复制代码
Debug和Trace的配置
开发者可以通过配置文件或代码来配置Debug和Trace的输出目标。
- using System.Diagnostics;
- // 创建文本写入器作为Trace监听器
- TextWriterTraceListener textListener = new TextWriterTraceListener("Output.log");
- Trace.Listeners.Add(textListener);
- // 创建控制台监听器
- ConsoleTraceListener consoleListener = new ConsoleTraceListener();
- Trace.Listeners.Add(consoleListener);
- // 自动刷新输出
- Trace.AutoFlush = true;
- // 使用Trace输出
- Trace.WriteLine("This message will appear in both console and log file");
- // 关闭监听器
- Trace.Close();
复制代码
在应用程序配置文件(app.config或web.config)中,可以配置Trace监听器:
- <configuration>
- <system.diagnostics>
- <trace autoflush="true">
- <listeners>
- <add name="consoleListener" type="System.Diagnostics.ConsoleTraceListener" />
- <add name="textListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="Output.log" />
- <add name="eventLogListener" type="System.Diagnostics.EventLogTraceListener" initializeData="MyApplication" />
- </listeners>
- </trace>
- </system.diagnostics>
- </configuration>
复制代码
Debug和Trace的输出级别
可以通过设置TraceLevel来控制输出的详细程度。
- using System.Diagnostics;
- // 设置Trace级别
- TraceSwitch traceSwitch = new TraceSwitch("General", "Entire Application");
- traceSwitch.Level = TraceLevel.Verbose;
- // 根据级别输出信息
- Trace.WriteLineIf(traceSwitch.TraceError, "Error message");
- Trace.WriteLineIf(traceSwitch.TraceWarning, "Warning message");
- Trace.WriteLineIf(traceSwitch.TraceInfo, "Info message");
- Trace.WriteLineIf(traceSwitch.TraceVerbose, "Verbose message");
复制代码
使用Debug和Trace进行性能分析
Debug和Trace类还可以用于简单的性能分析。
- using System.Diagnostics;
- // 开始计时
- Debug.WriteLine("Starting operation");
- Stopwatch stopwatch = Stopwatch.StartNew();
- // 执行一些操作
- Thread.Sleep(1000);
- // 停止计时并输出结果
- stopwatch.Stop();
- Debug.WriteLine($"Operation completed in {stopwatch.ElapsedMilliseconds} ms");
复制代码
高级调试技巧:条件输出、格式化输出等
条件编译符号
使用条件编译符号,可以控制代码是否被编译到程序中。
- #define DEBUG
- #define TRACE
- using System.Diagnostics;
- public class Program
- {
- public static void Main()
- {
- #if DEBUG
- Console.WriteLine("Debug version");
- #endif
- #if TRACE
- Console.WriteLine("Trace enabled");
- #endif
- #if DEBUG && TRACE
- Console.WriteLine("Both DEBUG and TRACE are defined");
- #endif
- }
- }
复制代码
Conditional特性
Conditional特性允许根据条件编译符号来决定是否调用方法。
- using System.Diagnostics;
- public class Logger
- {
- [Conditional("DEBUG")]
- public static void LogDebug(string message)
- {
- Console.WriteLine($"DEBUG: {message}");
- }
- [Conditional("TRACE")]
- public static void LogTrace(string message)
- {
- Console.WriteLine($"TRACE: {message}");
- }
- }
- public class Program
- {
- public static void Main()
- {
- Logger.LogDebug("This is a debug message");
- Logger.LogTrace("This is a trace message");
- }
- }
复制代码
Debugger类的高级用法
System.Diagnostics.Debugger类提供了与调试器交互的高级方法。
- using System.Diagnostics;
- public class Program
- {
- public static void Main()
- {
- // 检查是否附加了调试器
- if (Debugger.IsAttached)
- {
- Console.WriteLine("Debugger is attached");
- }
- // 启动调试器并附加到当前进程
- if (!Debugger.IsAttached)
- {
- Debugger.Launch();
- }
- // 设置断点(仅在调试器中有效)
- Debugger.Break();
- // 输出调试信息
- Debug.WriteLine("This is a debug message");
- }
- }
复制代码
使用DebuggerDisplay特性
DebuggerDisplay特性可以自定义对象在调试器中的显示方式。
- using System.Diagnostics;
- [DebuggerDisplay("Name = {Name}, Age = {Age}")]
- public class Person
- {
- public string Name { get; set; }
- public int Age { get; set; }
- }
- public class Program
- {
- public static void Main()
- {
- var person = new Person { Name = "Alice", Age = 30 };
- // 在调试器中,person对象将显示为 "Name = Alice, Age = 30"
- Console.WriteLine(person.Name);
- }
- }
复制代码
使用DebuggerStepThrough和DebuggerHidden特性
这些特性可以控制调试器如何处理特定方法。
- using System.Diagnostics;
- public class MathUtils
- {
- [DebuggerStepThrough]
- public static int Add(int a, int b)
- {
- // 调试器将单步执行此方法,而不是进入方法内部
- return a + b;
- }
- [DebuggerHidden]
- public static int Multiply(int a, int b)
- {
- // 调试器将完全隐藏此方法
- return a * b;
- }
- }
复制代码
使用TraceSource进行结构化跟踪
TraceSource类提供了更结构化的跟踪方式,允许定义不同的跟踪源和级别。
- using System.Diagnostics;
- public class Program
- {
- private static TraceSource traceSource = new TraceSource("MyApp");
- public static void Main()
- {
- // 配置TraceSource
- traceSource.Switch = new SourceSwitch("SourceSwitch", "All");
- traceSource.Listeners.Add(new ConsoleTraceListener());
- // 输出不同级别的跟踪信息
- traceSource.TraceEvent(TraceEventType.Error, 0, "Error message");
- traceSource.TraceEvent(TraceEventType.Warning, 0, "Warning message");
- traceSource.TraceEvent(TraceEventType.Information, 0, "Information message");
- traceSource.TraceEvent(TraceEventType.Verbose, 0, "Verbose message");
- // 关闭TraceSource
- traceSource.Close();
- }
- }
复制代码
使用CorrelationManager跟踪操作
CorrelationManager类可以帮助跟踪跨线程和跨活动的操作。
- using System.Diagnostics;
- public class Program
- {
- public static void Main()
- {
- Trace.CorrelationManager.ActivityId = Guid.NewGuid();
- Trace.CorrelationManager.StartLogicalOperation("MainOperation");
- Trace.WriteLine("Starting main operation");
- // 模拟子操作
- Trace.CorrelationManager.StartLogicalOperation("SubOperation");
- Trace.WriteLine("Starting sub operation");
- Trace.CorrelationManager.StopLogicalOperation();
- Trace.WriteLine("Sub operation completed");
- Trace.CorrelationManager.StopLogicalOperation();
- Trace.WriteLine("Main operation completed");
- }
- }
复制代码
日志记录框架:NLog、log4net、Serilog等
NLog使用指南
NLog是一个灵活且免费的日志记录平台,适用于各种.NET平台。
首先,通过NuGet安装NLog包:
可以通过代码或配置文件来配置NLog。
- using NLog;
- using NLog.Targets;
- using NLog.Config;
- public class Program
- {
- public static void Main()
- {
- // 创建日志配置
- var config = new LoggingConfiguration();
- // 创建控制台目标
- var consoleTarget = new ColoredConsoleTarget("console")
- {
- Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}"
- };
- // 创建文件目标
- var fileTarget = new FileTarget("file")
- {
- FileName = "${basedir}/logs/${shortdate}.log",
- Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}"
- };
- // 添加目标到配置
- config.AddTarget(consoleTarget);
- config.AddTarget(fileTarget);
- // 创建规则
- config.AddRule(LogLevel.Debug, LogLevel.Fatal, consoleTarget);
- config.AddRule(LogLevel.Debug, LogLevel.Fatal, fileTarget);
- // 应用配置
- LogManager.Configuration = config;
- // 获取日志记录器并记录日志
- var logger = LogManager.GetCurrentClassLogger();
- logger.Debug("This is a debug message");
- logger.Info("This is an info message");
- logger.Warn("This is a warning message");
- logger.Error("This is an error message");
- logger.Fatal("This is a fatal error message");
- }
- }
复制代码
在项目中添加NLog.config文件:
- <?xml version="1.0" encoding="utf-8" ?>
- <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- autoReload="true"
- throwExceptions="false">
- <targets>
- <target name="console" xsi:type="ColoredConsole"
- layout="${longdate}|${level:uppercase=true}|${logger}|${message}" />
-
- <target name="file" xsi:type="File"
- fileName="${basedir}/logs/${shortdate}.log"
- layout="${longdate}|${level:uppercase=true}|${logger}|${message}" />
- </targets>
-
- <rules>
- <logger name="*" minlevel="Debug" writeTo="console" />
- <logger name="*" minlevel="Debug" writeTo="file" />
- </rules>
- </nlog>
复制代码
然后在代码中使用:
- using NLog;
- public class Program
- {
- private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
- public static void Main()
- {
- Logger.Debug("This is a debug message");
- Logger.Info("This is an info message");
- Logger.Warn("This is a warning message");
- Logger.Error("This is an error message");
- Logger.Fatal("This is a fatal error message");
- }
- }
复制代码
log4net使用指南
log4net是另一个流行的日志记录框架,是Apache log4j框架的.NET移植版本。
通过NuGet安装log4net包:
可以通过代码或配置文件来配置log4net。
在App.config或Web.config中添加log4net配置:
- <configuration>
- <configSections>
- <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
- </configSections>
-
- <log4net>
- <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
- </layout>
- </appender>
-
- <appender name="FileAppender" type="log4net.Appender.FileAppender">
- <file value="logs/application.log" />
- <appendToFile value="true" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
- </layout>
- </appender>
-
- <root>
- <level value="DEBUG" />
- <appender-ref ref="ConsoleAppender" />
- <appender-ref ref="FileAppender" />
- </root>
- </log4net>
- </configuration>
复制代码
然后在代码中使用:
- using log4net;
- using log4net.Config;
- public class Program
- {
- private static readonly ILog Log = LogManager.GetLogger(typeof(Program));
- public static void Main()
- {
- // 配置log4net
- XmlConfigurator.Configure();
- // 记录日志
- Log.Debug("This is a debug message");
- Log.Info("This is an info message");
- Log.Warn("This is a warning message");
- Log.Error("This is an error message");
- Log.Fatal("This is a fatal error message");
- }
- }
复制代码
Serilog使用指南
Serilog是一个结构化日志记录库,支持丰富的日志数据结构。
通过NuGet安装Serilog包:
- Install-Package Serilog
- Install-Package Serilog.Sinks.Console
- Install-Package Serilog.Sinks.File
复制代码- using Serilog;
- public class Program
- {
- public static void Main()
- {
- // 配置Serilog
- Log.Logger = new LoggerConfiguration()
- .MinimumLevel.Debug()
- .WriteTo.Console()
- .WriteTo.File("logs/app-.txt", rollingInterval: RollingInterval.Day)
- .CreateLogger();
- // 记录结构化日志
- Log.Information("Hello, {Name}!", "World");
- // 记录带有属性的日志
- var position = new { Latitude = 25, Longitude = 134 };
- Log.Information("Processing {@Position}", position);
- // 记录不同级别的日志
- Log.Debug("This is a debug message");
- Log.Information("This is an info message");
- Log.Warning("This is a warning message");
- Log.Error("This is an error message");
- Log.Fatal("This is a fatal error message");
- // 关闭日志
- Log.CloseAndFlush();
- }
- }
复制代码
日志框架比较与选择
实际应用案例:不同场景下的最佳实践
控制台应用程序中的输出
在控制台应用程序中,通常需要直接与用户交互,因此输出应该清晰、易读。
- using System;
- using System.Threading;
- public class ConsoleApp
- {
- public static void Main()
- {
- // 设置控制台标题
- Console.Title = "My Console Application";
- // 显示欢迎信息
- Console.WriteLine("======================================");
- Console.WriteLine("= Welcome to My Application =");
- Console.WriteLine("======================================");
- Console.WriteLine();
- // 模拟进度显示
- Console.Write("Processing: ");
- for (int i = 0; i <= 100; i += 10)
- {
- Console.Write($"{i}% ");
- Thread.Sleep(200);
- }
- Console.WriteLine("\n");
- // 彩色输出重要信息
- Console.ForegroundColor = ConsoleColor.Green;
- Console.WriteLine("Operation completed successfully!");
- Console.ResetColor();
- // 用户输入
- Console.Write("Press any key to exit...");
- Console.ReadKey();
- }
- }
复制代码
ASP.NET Core应用程序中的日志记录
在ASP.NET Core应用程序中,日志记录对于监控和调试至关重要。
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
- using Serilog;
- public class Program
- {
- public static void Main(string[] args)
- {
- // 配置Serilog
- Log.Logger = new LoggerConfiguration()
- .MinimumLevel.Information()
- .WriteTo.Console()
- .WriteTo.File("logs/webapp-.txt", rollingInterval: RollingInterval.Day)
- .CreateLogger();
- try
- {
- Log.Information("Starting web host");
- CreateHostBuilder(args).Build().Run();
- }
- catch (Exception ex)
- {
- Log.Fatal(ex, "Host terminated unexpectedly");
- }
- finally
- {
- Log.CloseAndFlush();
- }
- }
- public static IHostBuilder CreateHostBuilder(string[] args) =>
- Host.CreateDefaultBuilder(args)
- .UseSerilog() // 使用Serilog作为日志提供程序
- .ConfigureWebHostDefaults(webBuilder =>
- {
- webBuilder.UseStartup<Startup>();
- });
- }
- public class Startup
- {
- private readonly ILogger<Startup> _logger;
- public Startup(ILogger<Startup> logger)
- {
- _logger = logger;
- }
- public void ConfigureServices(IServiceCollection services)
- {
- _logger.LogInformation("Configuring services");
- // 配置服务
- }
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- _logger.LogInformation("Configuring middleware");
-
- if (env.IsDevelopment())
- {
- _logger.LogDebug("In development environment");
- app.UseDeveloperExceptionPage();
- }
- app.UseRouting();
-
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapGet("/", async context =>
- {
- _logger.LogInformation("Processing request to /");
- await context.Response.WriteAsync("Hello World!");
- });
- });
- }
- }
复制代码
桌面应用程序中的调试输出
在桌面应用程序(如WPF或WinForms)中,调试输出对于开发过程中的问题诊断非常重要。
- using System;
- using System.Diagnostics;
- using System.Windows;
- namespace WpfApp
- {
- public partial class MainWindow : Window
- {
- public MainWindow()
- {
- InitializeComponent();
- Loaded += MainWindow_Loaded;
- }
- private void MainWindow_Loaded(object sender, RoutedEventArgs e)
- {
- // 使用Debug输出
- Debug.WriteLine("Application started");
- // 使用Trace输出
- Trace.WriteLine("Window loaded");
- // 条件输出
- bool debugMode = true;
- Debug.WriteLineIf(debugMode, "Debug mode is active");
- // 性能测量
- Stopwatch stopwatch = Stopwatch.StartNew();
- // 执行一些操作
- LoadData();
- stopwatch.Stop();
- Debug.WriteLine($"Data loaded in {stopwatch.ElapsedMilliseconds} ms");
- }
- private void LoadData()
- {
- // 模拟数据加载
- for (int i = 0; i < 100; i++)
- {
- Debug.WriteLine($"Loading item {i}");
- // 模拟工作
- System.Threading.Thread.Sleep(10);
- }
- }
- }
- }
复制代码
库和API中的日志记录
在开发库和API时,提供适当的日志记录可以帮助使用者更好地理解和使用你的代码。
- using Microsoft.Extensions.Logging;
- using System;
- public class MyApiService
- {
- private readonly ILogger<MyApiService> _logger;
- public MyApiService(ILogger<MyApiService> logger)
- {
- _logger = logger ?? throw new ArgumentNullException(nameof(logger));
- }
- public void ProcessData(string data)
- {
- try
- {
- _logger.LogInformation("Starting data processing");
-
- if (string.IsNullOrEmpty(data))
- {
- _logger.LogWarning("Empty data received");
- return;
- }
- // 模拟处理
- _logger.LogDebug("Processing data: {Data}", data);
-
- // 如果启用了详细日志,输出更多细节
- if (_logger.IsEnabled(LogLevel.Debug))
- {
- _logger.LogDebug("Data length: {Length}", data.Length);
- }
- // 实际处理逻辑
- var result = data.ToUpper();
-
- _logger.LogInformation("Data processed successfully");
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error processing data");
- throw;
- }
- }
- }
复制代码
多线程应用程序中的日志记录
在多线程应用程序中,日志记录需要考虑线程安全和上下文信息。
- using System;
- using System.Diagnostics;
- using System.Threading;
- using System.Threading.Tasks;
- public class MultiThreadedApp
- {
- private static readonly object _lock = new object();
-
- public static void Main()
- {
- // 配置Trace监听器
- Trace.Listeners.Add(new ConsoleTraceListener());
- Trace.AutoFlush = true;
- // 启动多个任务
- Task[] tasks = new Task[5];
- for (int i = 0; i < 5; i++)
- {
- int taskNum = i;
- tasks[i] = Task.Run(() => ProcessData(taskNum));
- }
- // 等待所有任务完成
- Task.WaitAll(tasks);
- Console.WriteLine("All tasks completed");
- }
- private static void ProcessData(int taskNum)
- {
- // 使用CorrelationManager跟踪活动
- Trace.CorrelationManager.ActivityId = Guid.NewGuid();
- Trace.CorrelationManager.StartLogicalOperation($"Task{taskNum}");
- try
- {
- Trace.WriteLine($"Task {taskNum} started on thread {Thread.CurrentThread.ManagedThreadId}");
- // 模拟工作
- for (int i = 0; i < 5; i++)
- {
- // 线程安全的日志记录
- lock (_lock)
- {
- Trace.WriteLine($"Task {taskNum}, Step {i}");
- }
- Thread.Sleep(100);
- }
- Trace.WriteLine($"Task {taskNum} completed");
- }
- finally
- {
- Trace.CorrelationManager.StopLogicalOperation();
- }
- }
- }
复制代码
性能考虑和优化
日志记录的性能影响
日志记录可能会对应用程序性能产生影响,特别是在高负载或高频日志记录的情况下。以下是一些性能考虑因素:
使用异步日志记录可以减少I/O操作对主线程的影响。
- using System.Threading.Tasks;
- using NLog;
- public class AsyncLoggingExample
- {
- private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
- public static async Task ProcessDataAsync()
- {
- Logger.Info("Starting async processing");
-
- // 模拟异步工作
- await Task.Delay(100);
-
- Logger.Info("Async processing completed");
- }
- }
复制代码
在记录复杂或耗时的日志消息前,检查日志级别是否启用。
- using Microsoft.Extensions.Logging;
- public class ConditionalLoggingExample
- {
- private readonly ILogger<ConditionalLoggingExample> _logger;
- public ConditionalLoggingExample(ILogger<ConditionalLoggingExample> logger)
- {
- _logger = logger;
- }
- public void ProcessLargeData(LargeDataObject data)
- {
- _logger.LogInformation("Processing large data");
-
- // 在记录复杂对象前检查日志级别
- if (_logger.IsEnabled(LogLevel.Debug))
- {
- // 序列化大型对象可能很耗时
- _logger.LogDebug("Data details: {@Data}", data);
- }
-
- // 处理数据...
- }
- }
- public class LargeDataObject
- {
- // 大型数据对象的属性
- }
复制代码
批量日志记录可以减少I/O操作次数,提高性能。
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Text;
- public class BatchLoggingExample
- {
- private readonly string _logFilePath;
- private readonly Queue<string> _logQueue;
- private readonly object _lock;
- private readonly int _batchSize;
- private readonly TimeSpan _flushInterval;
- private DateTime _lastFlushTime;
- public BatchLoggingExample(string logFilePath, int batchSize = 100, TimeSpan? flushInterval = null)
- {
- _logFilePath = logFilePath;
- _batchSize = batchSize;
- _flushInterval = flushInterval ?? TimeSpan.FromSeconds(5);
- _logQueue = new Queue<string>();
- _lock = new object();
- _lastFlushTime = DateTime.Now;
- }
- public void Log(string message)
- {
- lock (_lock)
- {
- _logQueue.Enqueue($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {message}");
- // 检查是否需要刷新
- if (_logQueue.Count >= _batchSize ||
- (DateTime.Now - _lastFlushTime) > _flushInterval)
- {
- Flush();
- }
- }
- }
- public void Flush()
- {
- if (_logQueue.Count == 0)
- return;
- var sb = new StringBuilder();
- while (_logQueue.Count > 0)
- {
- sb.AppendLine(_logQueue.Dequeue());
- }
- File.AppendAllText(_logFilePath, sb.ToString());
- _lastFlushTime = DateTime.Now;
- }
- }
复制代码
日志级别管理
合理使用日志级别可以减少不必要的日志记录,提高性能。
- using Microsoft.Extensions.Logging;
- public class LogLevelManagementExample
- {
- private readonly ILogger<LogLevelManagementExample> _logger;
- public LogLevelManagementExample(ILogger<LogLevelManagementExample> logger)
- {
- _logger = logger;
- }
- public void ProcessData(string data)
- {
- // 始终记录重要信息
- _logger.LogInformation("Processing data");
- // 仅在开发环境记录详细信息
- _logger.LogDebug("Data details: {Data}", data);
- try
- {
- // 处理数据...
-
- // 记录成功信息,但仅在Info级别启用时
- if (_logger.IsEnabled(LogLevel.Information))
- {
- _logger.LogInformation("Data processed successfully. Length: {Length}", data.Length);
- }
- }
- catch (Exception ex)
- {
- // 始终记录错误
- _logger.LogError(ex, "Error processing data");
- throw;
- }
- }
- }
复制代码
结构化日志 vs. 纯文本日志
结构化日志(如JSON格式)虽然可能占用更多空间,但提供了更好的查询和分析能力。
- using Serilog;
- using System;
- using System.Collections.Generic;
- public class StructuredLoggingExample
- {
- public static void Main()
- {
- Log.Logger = new LoggerConfiguration()
- .WriteTo.Console()
- .WriteTo.File("logs/structured.json", formatter: new Serilog.Formatting.Json.JsonFormatter())
- .CreateLogger();
- // 记录结构化日志
- var order = new
- {
- Id = 12345,
- Customer = "John Doe",
- Items = new[] { "Item1", "Item2", "Item3" },
- Total = 99.99,
- Date = DateTime.Now
- };
- Log.Information("Order processed: {@Order}", order);
- // 记录带有上下文的信息
- Log.ForContext("Department", "Sales")
- .ForContext("UserId", "user123")
- .Information("User action: {Action} on {Target}", "Update", "Order");
- Log.CloseAndFlush();
- }
- }
复制代码
日志轮转和清理
长时间运行的应用程序需要适当的日志轮转和清理机制,以防止日志文件占用过多磁盘空间。
- using System;
- using System.IO;
- using System.Linq;
- public class LogRotationExample
- {
- private readonly string _logDirectory;
- private readonly string _logFilePrefix;
- private readonly int _maxLogFiles;
- private readonly long _maxLogFileSize;
- public LogRotationExample(string logDirectory, string logFilePrefix, int maxLogFiles = 10, long maxLogFileSize = 10 * 1024 * 1024)
- {
- _logDirectory = logDirectory;
- _logFilePrefix = logFilePrefix;
- _maxLogFiles = maxLogFiles;
- _maxLogFileSize = maxLogFileSize;
- // 确保日志目录存在
- Directory.CreateDirectory(logDirectory);
- }
- public void Log(string message)
- {
- // 获取当前日志文件路径
- string currentLogPath = GetCurrentLogFilePath();
- // 检查当前日志文件是否存在以及是否超过大小限制
- if (File.Exists(currentLogPath) && new FileInfo(currentLogPath).Length > _maxLogFileSize)
- {
- // 轮转日志文件
- RotateLogFiles();
- currentLogPath = GetCurrentLogFilePath();
- }
- // 写入日志
- File.AppendAllText(currentLogPath, $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {message}{Environment.NewLine}");
- }
- private string GetCurrentLogFilePath()
- {
- return Path.Combine(_logDirectory, $"{_logFilePrefix}_current.log");
- }
- private void RotateLogFiles()
- {
- // 删除最旧的日志文件(如果超过最大数量)
- var logFiles = Directory.GetFiles(_logDirectory, $"{_logFilePrefix}_*.log")
- .OrderBy(f => f)
- .ToList();
- while (logFiles.Count >= _maxLogFiles)
- {
- File.Delete(logFiles[0]);
- logFiles.RemoveAt(0);
- }
- // 重命名当前日志文件
- string currentLogPath = GetCurrentLogFilePath();
- string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
- string archivedLogPath = Path.Combine(_logDirectory, $"{_logFilePrefix}_{timestamp}.log");
- if (File.Exists(currentLogPath))
- {
- File.Move(currentLogPath, archivedLogPath);
- }
- }
- }
复制代码
总结
本文全面介绍了C#中输出窗口信息显示的各种方法,从基础的Console.WriteLine到高级的Debug调试技巧。我们探讨了以下关键内容:
1. 基础输出方法:详细介绍了Console.WriteLine及其相关方法,包括格式化输出、颜色设置和窗口操作。
2. 调试输出:深入讲解了Debug和Trace类的使用,包括配置、输出级别和性能分析。
3. 高级调试技巧:探讨了条件编译、Conditional特性、Debugger类的高级用法等。
4. 日志记录框架:比较和介绍了NLog、log4net和Serilog等流行日志框架的使用方法。
5. 实际应用案例:提供了不同场景下的最佳实践,包括控制台应用、ASP.NET Core应用、桌面应用、库和API以及多线程应用中的日志记录。
6. 性能考虑和优化:讨论了日志记录的性能影响,以及如何通过异步日志记录、条件日志记录、批量日志记录等技术优化性能。
基础输出方法:详细介绍了Console.WriteLine及其相关方法,包括格式化输出、颜色设置和窗口操作。
调试输出:深入讲解了Debug和Trace类的使用,包括配置、输出级别和性能分析。
高级调试技巧:探讨了条件编译、Conditional特性、Debugger类的高级用法等。
日志记录框架:比较和介绍了NLog、log4net和Serilog等流行日志框架的使用方法。
实际应用案例:提供了不同场景下的最佳实践,包括控制台应用、ASP.NET Core应用、桌面应用、库和API以及多线程应用中的日志记录。
性能考虑和优化:讨论了日志记录的性能影响,以及如何通过异步日志记录、条件日志记录、批量日志记录等技术优化性能。
通过掌握这些技术和方法,开发者可以更有效地输出和显示信息,提高调试效率,增强应用程序的可维护性和可监控性。无论是简单的控制台应用程序还是复杂的企业级系统,合理的输出和日志策略都是成功开发和维护软件的关键因素。
在实际开发中,应根据应用程序的需求、性能要求和运行环境选择合适的输出和日志记录方法。同时,始终记住日志记录的目的是为了帮助开发和运维人员更好地理解和维护系统,因此应保持日志信息的清晰、相关和可操作。 |
|