【问题标题】:On a C# Web Service can I find a unique thread ID or some ID for logging purposes?在 C# Web 服务上,我可以找到一个唯一的线程 ID 或一些用于日志记录的 ID?
【发布时间】:2023-04-07 13:11:01
【问题描述】:
我在 C# .NET 3.5 中运行 Web 服务。我想记录各种电话。然而,由于许多用户同时使用相同的功能,因此很难判断哪个日志调用属于哪个。
在 C++ 生活中,我们使用了线程 ID。 C# 中的等价物是什么?
我试过了
System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess();
proc.Id;
但是,这每次都会让我得到相同的 ID。
【问题讨论】:
标签:
c#
.net
web-services
multithreading
【解决方案1】:
也许 Thread.CurrentThread.ManagedThreadId
【解决方案2】:
如果你使用 MS Ent Lib 和他们的记录器,你可以使用 Tracer 类来获得一些不错的记录:
例子
public Output MyServiceMethod(Input input, string transactionId)
{
using(new Tracer("MyServiceMethod: " + transactionId))
{
... stuff ...
return output;
}
}
您甚至可以嵌套示踪剂。 using 中的所有日志记录都将具有您为 Tracer 构造函数提供的字符串作为扩展属性。
【解决方案3】:
您可以使用Thread.CurrentThread.ManagedThreadId。
【解决方案4】:
我会用
System.Threading.Thread.CurrentThread.ManagedThreadId
此外,由于这是一项 Web 服务,如果客户端来自不同的 IP 地址,您也可以将其记录下来,这可能有助于记录/诊断。
【解决方案5】:
如果您使用一些日志框架,例如 log4net,您会注意到线程 ID 会自动为您记录。
这很容易上手。
【解决方案6】:
看看 ASP.NET 健康监控。见ASP.NET Health Monitoring Overview。它默认记录的事件包含的信息比您可能想要的更多:
日志名称:应用程序
来源:ASP.NET 2.0.50727.0
日期:2/12/2009 12:57:14
事件编号:1309
任务类别:网络事件
级别:警告
关键词:经典
用户:不适用
电脑:笔记本电脑
描述:
事件代码:3005
事件消息:发生未处理的异常。
活动时间:2/12/2009 12:57:14
活动时间(UTC):2/12/2009 17:57:14
事件 ID:b08e9d3be7364690a660254dc0a29b6d
事件顺序:5
事件发生:4
事件详细代码:0
应用信息:
应用域:bba4cebc-1-128789349683310000
信任级别:完全
应用程序虚拟路径:/
应用程序路径:C:\Users\John Saunders\Documents\MVP\projects\WebServices\GeneralSoln\WebService1\
机器名称:笔记本电脑
处理信息:
进程号:11560
进程名称:WebDev.WebServer.exe
帐户名称:笔记本电脑\约翰桑德斯
异常信息:
异常类型:MissingMethodException
异常消息:找不到方法:'无效 System.ServiceModel.Diagnostics.EventLogger.UnsafeLogEvent(System.Diagnostics.TraceEventType,System.ServiceModel.Diagnostics.EventLogCategory,System.ServiceModel.Diagnostics.EventLogEventId,Boolean,System.String[])' .
索取资料:
请求网址:http://localhost:5305/Enumerations.asmx
请求路径:/Enumerations.asmx
用户主机地址:127.0.0.1
用户:
是否经过身份验证:假
认证类型:
线程帐户名称:Laptop\John Saunders
线程信息:
线程 ID:4
线程帐户名称:Laptop\John Saunders
是否冒充:假
堆栈跟踪:在 System.Runtime.CompilerServices.RuntimeHelpers.PrepareDelegate(Delegate d)
在 System.AppDomain.add_UnhandledException(UnhandledExceptionEventHandler 值)
在 System.ServiceModel.ServiceHostingEnvironment.HookADUnhandledExceptionEvent()
在 System.ServiceModel.ServiceHostingEnvironment.EnsureInitialized()
在 System.ServiceModel.ServiceHostingEnvironment.OnEnsureInitialized(对象状态)
在 System.ServiceModel.PartialTrustHelpers.PartialTrustInvoke(ContextCallback 回调,对象状态)
在 System.ServiceModel.ServiceHostingEnvironment.SafeEnsureInitialized()
在 System.ServiceModel.Activation.HttpModule.ProcessRequest(对象发送者,EventArgs e)
在 System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
在 System.Web.HttpApplication.ExecuteStep(IExecutionStep 步骤,Boolean& completedSynchronously)
自定义活动详情:
事件 XML: