文章目录
- 前言
- Nuget 环境安装
- 代码
- 使用
- 打印结果
- 总结
前言
有时候我们想要靠打印获得程序信息,因为Dubeg模式需要一点一点断点进入进出,但是我们觉得断点运行实在是太慢了,还是直接打印后找结果会好一点。
Nuget 环境安装
想自己写的话可以看我之前的文章
C# 控制台彩色打印
代码
新建一个Utils,里面放一个LogHelper
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Console = Colorful.Console;
namespace PubSubTest.Utils
{
public static class LogHelper
{
/// <summary>
/// 打印等级
/// </summary>
public static int PrintLevel = 0;
/// <summary>
/// 堆栈追踪
/// </summary>
/// <param name="deep">追踪深度,0为打印当前,1为打印上一层</param>
/// <returns></returns>
private static string TraceMethodInfo(int deep)
{
//Color.Brown
deep += 2;
string info = "";
try
{
StackFrame st = new System.Diagnostics.StackTrace(deep, true).GetFrame(0);
info = $"{st.GetMethod().DeclaringType.FullName} :{st.GetFileLineNumber()}";
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
//Color.Brown;
return info;
}
/// <summary>
/// 彩色深度打印
/// </summary>
/// <param name="msg">信息</param>
/// <param name="deep">深度</param>
/// <param name="state">等级</param>
public static void Log(string msg, int deep = 0, LogLevel state = LogLevel.Debug)
{
if ((int)state >= PrintLevel)
{
ColorPrint($"{state.ToString()}\t" +msg, (int)state);
var deepMsg = TraceMethodInfo(deep);
Console.WriteLine("\t" + deepMsg, (int)state);
}
}
private static void ColorPrint(string msg, int state)
{
switch (state)
{
case 0:
Console.WriteLine(msg);
break;
case 1:
Console.WriteLine(msg, Color.LightGreen);
break;
case 2:
Console.WriteLine(msg, Color.Yellow);
break;
case 3:
Console.WriteLine(msg, Color.Red);
break;
case 4:
Console.WriteLine(msg, Color.LightPink);
break;
}
}
}
/// <summary>
/// 日志等级
/// </summary>
public enum LogLevel : int
{
Debug = 0,
Info = 1,
Warn = 2,
Error = 3,
Must = 4
}
}
Tips:using Console = Colorful.Console;这句话别忘记了
使用
internal class Program
{
public static Action action;
public static PubSubHelper helper = new PubSubHelper();
static void Main(string[] args)
{
Test();
//Console.WriteLine(LogLevel.Warn.ToString());
Console.ReadLine();
}
public static void Test()
{
LogHelper.Log("打印测试",0);
LogHelper.Log("打印测试",1);
LogHelper.Log("打印测试",1,LogLevel.Debug);
LogHelper.Log("打印测试",1,LogLevel.Info);
LogHelper.Log("打印测试",1,LogLevel.Warn);
LogHelper.Log("打印测试",1,LogLevel.Error);
LogHelper.Log("打印测试",1,LogLevel.Must);
}
}
打印结果
总结
大家可以根据深度和色彩自己自定义工具输出。