记录最佳做法 [英] Logging best practices

查看:84
本文介绍了记录最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得有关人们如何在实际应用程序中处理跟踪和日志记录的故事.以下是一些可能有助于解释您答案的问题.

框架

您使用什么框架?

  • log4net
  • System.Diagnostics.Trace
  • System.Diagnostics.TraceSource
  • 记录应用程序块
  • 其他?

如果使用跟踪,是否使用Trace.Correlation.StartLogicalOperation?

您是手动编写此代码,还是使用某种形式的面向方面的编程来做到这一点?想要共享一个代码段吗?

您是否在跟踪源上提供任何形式的粒度?例如,WPF TraceSources允许您在各个级别进行配置:

  • System.Windows-所有WPF的设置
  • System.Windows.Animation-专门用于动画的替代.

听众

您使用什么日志输出?

  • 文本文件
  • XML文件
  • 事件日志
  • 其他?

如果使用文件,是使用滚动日志还是仅使用一个文件?您如何使日志可供人们使用?

查看

您使用哪些工具查看日志?

  • 记事本
  • 尾巴
  • 事件查看器
  • 系统中心运营经理/Microsoft Operations Manager
  • WCF服务跟踪查看器
  • 其他?

如果要构建ASP.NET解决方案,是否还使用ASP.NET运行状况监视?您是否在运行状况监视器事件中包括跟踪输出?那么Trace.axd呢?

关于自定义性能计数器呢?

解决方案


更新:有关System.Diagnostics的扩展,提供了您可能需要的某些缺少的侦听器,请参阅CodePlex上的Essential.Diagnostics(

您可能不知道的功能:

  • 使用带格式字符串和args的TraceEvent重载可以帮助提高性能,因为将参数保留为单独的引用,直到Filter.ShouldTrace()成功.这意味着在系统确认消息将被实际记录之前,不会对参数值进行昂贵的ToString()调用.
  • Trace.CorrelationManager允许您将有关同一逻辑操作的日志语句关联起来(请参见下文).
  • VisualBasic.Logging.FileLogTraceListener非常适合写入日志文件,并支持文件旋转.尽管在VisualBasic名称空间中,但只需包含DLL,就可以在C#(或其他语言)项目中轻松使用它.
  • 在使用EventLogTraceListener时,如果您使用多个参数并使用空或null格式的字符串调用TraceEvent,则如果您使用的是本地化的消息资源,则args将直接传递给EventLog.WriteEntry().
  • Service Trace Viewer工具(来自WCF)对于查看与活动相关的日志文件的图形很有用(即使您未使用WCF).这确实可以帮助调试涉及多个线程/活动的复杂问题.
  • 通过清除所有侦听器(或删除默认值)来避免开销;否则,Default会将所有内容传递给跟踪系统(并产生所有这些ToString()开销).

可能需要扩展的区域(如果需要):

  • 数据库跟踪侦听器
  • 彩色控制台跟踪侦听器
  • MSMQ/电子邮件/WMI跟踪侦听器(如果需要)
  • 实施FileSystemWatcher调用Trace.Refresh进行动态配置更改

其他建议:

使用结构化事件ID,并保留一个引用列表(例如,将它们记录在枚举中).

对于系统中的每个(重要)事件,都具有唯一的事件ID,对于关联和查找特定问题非常有用.追溯到记录/使用事件ID的特定代码很容易,并且可以很容易地为常见错误提供指导,例如错误5178表示您的数据库连接字符串错误,等等.

事件ID应当采用某种结构(类似于电子邮件和HTTP中使用的回复代码理论),这样您就可以按类别对待它们,而无需知道特定的代码.

例如第一位数字可以详细说明通用类别:1xxx可以用于开始"操作,2xxx可以用于正常行为,3xxx可以用于活动跟踪,4xxx可以用于警告,5xxx可以用于错误,8xxx可以用于停止"操作,9xxx可以用于致命错误,等等.

第二个数字可以详细说明该区域,例如数据库信息为21xx(数据库警告为41xx,数据库错误为51xx),计算模式为22xx(计算警告为42xx等),其他模块为23xx等.

分配的结构化事件ID还允许您在过滤器中使用它们.

问:如果使用跟踪,是否使用Trace.Correlation.StartLogicalOperation?

A:Trace.CorrelationManager对于在任何类型的多线程环境(近来几乎是任何事情)中关联日志语句非常有用.

您至少需要为每个逻辑操作设置一次ActivityId以便关联.

启动/停止和LogicalOperationStack然后可以用于基于简单堆栈的上下文.对于更复杂的上下文(例如异步操作),将TraceTransfer应用于新的ActivityId(在更改之前)允许关联.

Service Trace Viewer工具可用于查看活动图(即使您未使用WCF).

问:您是手动编写此代码还是使用某种形式的面向方面的编程来完成此操作?想要共享一个代码段吗?

A:您可能要创建一个范围类,例如LogicalOperationScope,即(a)在创建时设置上下文,并且(b)在处理时重置上下文.

这使您可以编写如下代码来自动包装操作:

  using( LogicalOperationScope operation = new LogicalOperationScope("Operation") )
  {
    // .. do work here
  }

创建时,作用域可以首先根据需要设置ActivityId,调用StartLogicalOperation,然后记录TraceEventType.Start消息.在Dispose上,它可能会记录一条Stop消息,然后调用StopLogicalOperation.

问:您是否提供跟踪来源的任何形式的粒度?例如,WPF TraceSources允许您在各个级别进行配置.

A:是的,随着系统的变大,多个跟踪源非常有用/重要.

虽然您可能希望始终记录所有警告&以上或所有信息和技术"以上消息,对于任何大小合理的系统,活动跟踪(开始,停止等)和详细日志记录的数量都变得太多了.

不仅可以一次打开或关闭所有开关,还可以一次为系统的一个部分打开此信息.

这样,您可以从通常的日志记录中查找重大问题(所有警告,错误等),然后在所需部分上放大"并将其设置为活动跟踪"或什至调试"级别.

所需的跟踪源数量取决于您的应用程序,例如您可能需要每个程序集或应用程序每个主要部分一个跟踪源.

如果您需要更精细的控制,请添加单个布尔开关以打开/关闭特定的高音量跟踪,例如原始邮件转储. (或者可以使用单独的跟踪源,类似于WCF/WPF).

您可能还需要为活动跟踪与常规(其他)日志记录考虑单独的跟踪源,因为它可以使按所需的方式精确配置过滤器变得容易一些.

请注意,即使使用了不同的来源,消息仍可以通过ActivityId进行关联,因此请根据需要使用尽可能多的消息.


听众

问:您使用什么日志输出?

这可能取决于您正在编写的应用程序类型以及正在记录的内容.通常,不同的东西会放在不同的位置(即多个输出).

我通常将输出分为三类:

(1)事件-Windows事件日志(和跟踪文件)

例如如果编写服务器/服务,则Windows上的最佳实践是使用Windows事件日志(您没有要向其报告的UI).

在这种情况下,所有致命,错误,警告和(服务级别)信息事件都应转到Windows事件日志中.信息级别应该为这些类型的高级事件保留,例如您要在事件日志中进行的事件. 服务已启动",服务已停止",已连接到Xyz",甚至可能是计划已启动",用户登录"等.

在某些情况下,您可能希望将事件日志写入应用程序的内置部分,而不是通过跟踪系统(即,直接写入事件日志条目).这意味着它不会被意外关闭. (请注意,您仍然还希望在跟踪系统中记录相同的事件,以便您可以进行关联.)

相反,Windows GUI应用程序通常会将这些报告给用户(尽管他们也可能会记录到Windows事件日志中).

事件还可能具有相关的性能计数器(例如,错误数/秒),协调任何直接写入事件日志,性能计数器,写入跟踪系统并报告给用户的操作可能很重要.它们同时发生.

即如果用户在特定时间看到错误消息,则应该能够在Windows事件日志中找到相同的错误消息,然后在跟踪日志中找到具有相同时间戳的同一事件(以及其他跟踪详细信息). /p>

(2)活动-应用程序日志文件或数据库表(和跟踪文件)

这是系统执行的常规活动,例如网页,已提交的股票市场交易,已接受订单,已执行计算等.

此处(以正确的粒度),活动跟踪(开始,停止等)很有用.

此外,使用特定的应用程序日志(有时也称为审核日志)非常普遍.通常,这是数据库表或应用程序日志文件,其中包含结构化数据(即一组字段).

根据您的应用程序,这里的内容可能会变得有些模糊.一个很好的例子是一个Web服务器,它将每个请求写入Web日志.类似的示例可能是消息传递系统或计算系统,其中记录了每个操作以及特定于应用程序的详细信息.

一个不太好的例子是股票交易或销售订购系统.在这些系统中,您可能已经在记录活动,因为它们具有重要的业务价值,但是将其与其他操作相关联的原理仍然很重要.

除自定义应用程序日志外,活动通常还具有相关的性能计数器,例如每秒的事务数.

通常,您应该协调不同系统之间的活动日志记录,即,在增加性能计数器并记录到跟踪系统的同时,将其写入应用程序日志.如果您同时执行所有操作(或在代码中彼此直接执行),则调试问题会比调试问题更容易(比它们都在代码中的不同时间/位置发生的情况要容易得多).

(3)调试跟踪-文本文件,或者XML或数据库.

这是详细级别或更低级别的信息(例如,用于打开/关闭原始数据转储的自定义布尔开关).这提供了在子活动级别上系统正在执行的任务的详细信息或详细信息.

这是您希望能够为应用程序的各个部分打开/关闭的级别(因此有多个来源).您不希望这些东西弄乱Windows事件日志.有时会使用数据库,但很有可能会在一定时间后清除滚动日志文件.

此信息与应用程序日志文件之间的最大区别是它是非结构化的.虽然应用程序日志可能具有``收件人'',``发件人'',``金额''等字段,但详细的调试跟踪可能是程序员输入的任何内容,例如检查值X = {value},Y = false",或随机注释/标记,例如完成,然后重试".

一种重要的做法是确保您放入应用程序日志文件中的内容或Windows事件日志也以相同的详细信息(例如时间戳)记录到跟踪系统中.这样一来,您便可以在调查时关联不同的日志.

如果由于复杂的关联而打算使用特定的日志查看器,例如服务跟踪查看器,则您需要使用适当的格式,即XML.否则,一个简单的文本文件通常就足够了-在较低的级别上,信息基本上是非结构化的,因此您可能会发现数组的转储,堆栈的转储等.如果可以在较高级别上与更结构化的日志相关联,则应该没事.

问:如果使用文件,您使用滚动日志还是仅使用一个文件?您如何使日志可供人们使用?

A:对于文件,通常您希望从可管理性的角度滚动日志文件(使用System.Diagnostics只需使用VisualBasic.Logging.FileLogTraceListener).

可用性是否再次取决于系统.如果您只是在谈论文件,那么对于服务器/服务来说,只是在必要时才可以访问滚动文件. (Windows事件日志或数据库应用程序日志将具有其自己的访问机制).

如果您不能轻松访问文件系统,则对数据库的调试跟踪可能会更容易. [IE.实现数据库TraceListener].

我为Windows GUI应用程序看到的一个有趣的解决方案是,它在运行时将非常详细的跟踪信息记录到飞行记录器"中,然后在没有问题的情况下将其关闭时,它只是删除了文件.

但是,如果崩溃或遇到问题,则说明该文件未被删除.如果它捕获到错误,或者下次运行,它将注意到该文件,然后它可以采取措施,例如压缩(例如7zip)并通过电子邮件发送或以其他方式提供.

如今,许多系统都将故障自动报告提交给中央服务器(例如,出于隐私原因与用户核实之后).


正在观看

问:您使用哪些工具查看日志?

A:如果出于不同原因有多个日志,则将使用多个查看器.

Notepad/vi/Notepad ++或任何其他文本编辑器是纯文本日志的基础.

如果您有复杂的操作,例如与转移相关的活动,那么您显然会使用诸如Service Trace Viewer之类的专用工具. (但是,如果您不需要它,则文本编辑器会更容易).

由于我通常将高级信息记录到Windows事件日志中,因此它提供了一种以结构化方式获得概述的快速方法(查找漂亮的错误/警告图标).尽管日志至少为您提供了一个起点,但您仅需要在日志中没有足够的文本时就开始搜索文本文件. (此时,确保您的日志具有协调一致的整体将很有用).

通常,Windows事件日志还会使这些重要事件可用于MOM或OpenView之类的监视工具.

其他-

如果您登录到数据库,则可以轻松地对信息进行过滤和排序(例如,放大特定的活动ID.(对于文本文件,您可以使用Grep/PowerShell或类似工具在所需的特定GUID上进行过滤)

MS Excel(或其他电子表格程序).如果可以使用正确的定界符将其导入,以便将不同的值放在不同的列中,则这对于分析结构化或半结构化信息很有用.

在调试/测试中运行服务时,为了简化起见,我通常将其托管在控制台应用程序中,我发现彩色控制台记录器很有用(例如,红色表示错误,黄色表示警告等).您需要实现自定义跟踪侦听器.

请注意,该框架不包括彩色控制台记录器或数据库记录器,因此,现在,如果需要它们,则需要编写它们(这不太难).

确实让我感到烦恼的是,几个框架(log4net,EntLib等)浪费了时间重新发明轮子,并重新实现了基本的日志记录,筛选和日志记录到文本文件,Windows事件日志和XML文件,以它们自己的不同方式(每个日志语句都不同);然后,每个人都实现了自己的版本,例如,数据库记录器,而现在大多数已经存在,而所需的只是几个System.Diagnostics的跟踪侦听器.谈论大量的重复劳动.

问:如果要构建ASP.NET解决方案,是否还使用ASP.NET运行状况监视?您是否在运行状况监视器事件中包括跟踪输出?那么Trace.axd呢?

这些东西可以根据需要打开/关闭.我发现Trace.axd对于调试服务器如何响应某些事情非常有用,但是在频繁使用的环境或长期跟踪中通常没有用.

问:自定义性能计数器如何?

对于专业的应用程序,尤其是服务器/服务,我希望它可以同时使用Performance Monitor计数器和日志记录到Windows事件日志中.这些是Windows中的标准工具,应该使用.

您需要确保包括用于所使用的性能计数器和事件日志的安装程序;这些应在安装时(以管理员身份安装时)创建.当您的应用正常运行时,它不需要管理权限(因此将无法创建丢失的日志).

这是练习以非管理员身份进行开发的好理由(有一个单独的admin帐户用于何时需要安装服务等).如果写入事件日志,.NET将在您第一次写入事件日志时自动创建一个丢失的日志.如果您是以非管理员身份开发的,则您会及早发现这一点,并避免在客户安装您的系统后由于客户未以管理员身份运行而无法使用该系统时感到讨厌.

I'd like to get stories on how people are handling tracing and logging in real applications. Here are some questions that might help to explain your answer.

Frameworks

What frameworks do you use?

  • log4net
  • System.Diagnostics.Trace
  • System.Diagnostics.TraceSource
  • Logging application block
  • Other?

If you use tracing, do you make use of Trace.Correlation.StartLogicalOperation?

Do you write this code manually, or do you use some form of aspect oriented programming to do it? Care to share a code snippet?

Do you provide any form of granularity over trace sources? E.g., WPF TraceSources allow you to configure them at various levels:

  • System.Windows - settings for all of WPF
  • System.Windows.Animation - override specifically for Animation.

Listeners

What log outputs do you use?

  • Text files
  • XML files
  • Event log
  • Other?

If using files, do you use rolling logs or just a single file? How do you make the logs available for people to consume?

Viewing

What tools to you use for viewing the logs?

  • Notepad
  • Tail
  • Event viewer
  • Systems Center Operations Manager/Microsoft Operations Manger
  • WCF Service Trace Viewer
  • Other?

If you are building an ASP.NET solution, do you also use ASP.NET Health Monitoring? Do you include trace output in the health monitor events? What about Trace.axd?

What about custom performance counters?

解决方案


Update: For extensions to System.Diagnostics, providing some of the missing listeners you might want, see Essential.Diagnostics on CodePlex (http://essentialdiagnostics.codeplex.com/)


Frameworks

Q: What frameworks do you use?

A: System.Diagnostics.TraceSource, built in to .NET 2.0.

It provides powerful, flexible, high performance logging for applications, however many developers are not aware of its capabilities and do not make full use of them.

There are some areas where additional functionality is useful, or sometimes the functionality exists but is not well documented, however this does not mean that the entire logging framework (which is designed to be extensible) should be thrown away and completely replaced like some popular alternatives (NLog, log4net, Common.Logging, and even EntLib Logging).

Rather than change the way you add logging statements to your application and re-inventing the wheel, just extended the System.Diagnostics framework in the few places you need it.

It seems to me the other frameworks, even EntLib, simply suffer from Not Invented Here Syndrome, and I think they have wasted time re-inventing the basics that already work perfectly well in System.Diagnostics (such as how you write log statements), rather than filling in the few gaps that exist. In short, don't use them -- they aren't needed.

Features you may not have known:

  • Using the TraceEvent overloads that take a format string and args can help performance as parameters are kept as separate references until after Filter.ShouldTrace() has succeeded. This means no expensive calls to ToString() on parameter values until after the system has confirmed message will actually be logged.
  • The Trace.CorrelationManager allows you to correlate log statements about the same logical operation (see below).
  • VisualBasic.Logging.FileLogTraceListener is good for writing to log files and supports file rotation. Although in the VisualBasic namespace, it can be just as easily used in a C# (or other language) project simply by including the DLL.
  • When using EventLogTraceListener if you call TraceEvent with multiple arguments and with empty or null format string, then the args are passed directly to the EventLog.WriteEntry() if you are using localized message resources.
  • The Service Trace Viewer tool (from WCF) is useful for viewing graphs of activity correlated log files (even if you aren't using WCF). This can really help debug complex issues where multiple threads/activites are involved.
  • Avoid overhead by clearing all listeners (or removing Default); otherwise Default will pass everything to the trace system (and incur all those ToString() overheads).

Areas you might want to look at extending (if needed):

  • Database trace listener
  • Colored console trace listener
  • MSMQ / Email / WMI trace listeners (if needed)
  • Implement a FileSystemWatcher to call Trace.Refresh for dynamic configuration changes

Other Recommendations:

Use structed event id's, and keep a reference list (e.g. document them in an enum).

Having unique event id's for each (significant) event in your system is very useful for correlating and finding specific issues. It is easy to track back to the specific code that logs/uses the event ids, and can make it easy to provide guidance for common errors, e.g. error 5178 means your database connection string is wrong, etc.

Event id's should follow some kind of structure (similar to the Theory of Reply Codes used in email and HTTP), which allows you to treat them by category without knowing specific codes.

e.g. The first digit can detail the general class: 1xxx can be used for 'Start' operations, 2xxx for normal behaviour, 3xxx for activity tracing, 4xxx for warnings, 5xxx for errors, 8xxx for 'Stop' operations, 9xxx for fatal errors, etc.

The second digit can detail the area, e.g. 21xx for database information (41xx for database warnings, 51xx for database errors), 22xx for calculation mode (42xx for calculation warnings, etc), 23xx for another module, etc.

Assigned, structured event id's also allow you use them in filters.

Q: If you use tracing, do you make use of Trace.Correlation.StartLogicalOperation?

A: Trace.CorrelationManager is very useful for correlating log statements in any sort of multi-threaded environment (which is pretty much anything these days).

You need at least to set the ActivityId once for each logical operation in order to correlate.

Start/Stop and the LogicalOperationStack can then be used for simple stack-based context. For more complex contexts (e.g. asynchronous operations), using TraceTransfer to the new ActivityId (before changing it), allows correlation.

The Service Trace Viewer tool can be useful for viewing activity graphs (even if you aren't using WCF).

Q: Do you write this code manually, or do you use some form of aspect oriented programming to do it? Care to share a code snippet?

A: You may want to create a scope class, e.g. LogicalOperationScope, that (a) sets up the context when created and (b) resets the context when disposed.

This allows you to write code such as the following to automatically wrap operations:

  using( LogicalOperationScope operation = new LogicalOperationScope("Operation") )
  {
    // .. do work here
  }

On creation the scope could first set ActivityId if needed, call StartLogicalOperation and then log a TraceEventType.Start message. On Dispose it could log a Stop message, and then call StopLogicalOperation.

Q: Do you provide any form of granularity over trace sources? E.g., WPF TraceSources allow you to configure them at various levels.

A: Yes, multiple Trace Sources are useful / important as systems get larger.

Whilst you probably want to consistently log all Warning & above, or all Information & above messages, for any reasonably sized system the volume of Activity Tracing (Start, Stop, etc) and Verbose logging simply becomes too much.

Rather than having only one switch that turns it all either on or off, it is useful to be able to turn on this information for one section of your system at a time.

This way, you can locate significant problems from the usually logging (all warnings, errors, etc), and then "zoom in" on the sections you want and set them to Activity Tracing or even Debug levels.

The number of trace sources you need depends on your application, e.g. you may want one trace source per assembly or per major section of your application.

If you need even more fine tuned control, add individual boolean switches to turn on/off specific high volume tracing, e.g. raw message dumps. (Or a separate trace source could be used, similar to WCF/WPF).

You might also want to consider separate trace sources for Activity Tracing vs general (other) logging, as it can make it a bit easier to configure filters exactly how you want them.

Note that messages can still be correlated via ActivityId even if different sources are used, so use as many as you need.


Listeners

Q: What log outputs do you use?

This can depend on what type of application you are writing, and what things are being logged. Usually different things go in different places (i.e. multiple outputs).

I generally classify outputs into three groups:

(1) Events - Windows Event Log (and trace files)

e.g. If writing a server/service, then best practice on Windows is to use the Windows Event Log (you don't have a UI to report to).

In this case all Fatal, Error, Warning and (service-level) Information events should go to the Windows Event Log. The Information level should be reserved for these type of high level events, the ones that you want to go in the event log, e.g. "Service Started", "Service Stopped", "Connected to Xyz", and maybe even "Schedule Initiated", "User Logged On", etc.

In some cases you may want to make writing to the event log a built-in part of your application and not via the trace system (i.e. write Event Log entries directly). This means it can't accidentally be turned off. (Note you still also want to note the same event in your trace system so you can correlate).

In contrast, a Windows GUI application would generally report these to the user (although they may also log to the Windows Event Log).

Events may also have related performance counters (e.g. number of errors/sec), and it can be important to co-ordinate any direct writing to the Event Log, performance counters, writing to the trace system and reporting to the user so they occur at the same time.

i.e. If a user sees an error message at a particular time, you should be able to find the same error message in the Windows Event Log, and then the same event with the same timestamp in the trace log (along with other trace details).

(2) Activities - Application Log files or database table (and trace files)

This is the regular activity that a system does, e.g. web page served, stock market trade lodged, order taken, calculation performed, etc.

Activity Tracing (start, stop, etc) is useful here (at the right granuality).

Also, it is very common to use a specific Application Log (sometimes called an Audit Log). Usually this is a database table or an application log file and contains structured data (i.e. a set of fields).

Things can get a bit blurred here depending on your application. A good example might be a web server which writes each request to a web log; similar examples might be a messaging system or calculation system where each operation is logged along with application-specific details.

A not so good example is stock market trades or a sales ordering system. In these systems you are probably already logging the activity as they have important business value, however the principal of correlating them to other actions is still important.

As well as custom application logs, activities also often have related peformance counters, e.g. number of transactions per second.

In generally you should co-ordinate logging of activities across different systems, i.e. write to your application log at the same time as you increase your performance counter and log to your trace system. If you do all at the same time (or straight after each other in the code), then debugging problems is easier (than if they all occur at diffent times/locations in the code).

(3) Debug Trace - Text file, or maybe XML or database.

This is information at Verbose level and lower (e.g. custom boolean switches to turn on/off raw data dumps). This provides the guts or details of what a system is doing at a sub-activity level.

This is the level you want to be able to turn on/off for individual sections of your application (hence the multiple sources). You don't want this stuff cluttering up the Windows Event Log. Sometimes a database is used, but more likely are rolling log files that are purged after a certain time.

A big difference between this information and an Application Log file is that it is unstructured. Whilst an Application Log may have fields for To, From, Amount, etc., Verbose debug traces may be whatever a programmer puts in, e.g. "checking values X={value}, Y=false", or random comments/markers like "Done it, trying again".

One important practice is to make sure things you put in application log files or the Windows Event Log also get logged to the trace system with the same details (e.g. timestamp). This allows you to then correlate the different logs when investigating.

If you are planning to use a particular log viewer because you have complex correlation, e.g. the Service Trace Viewer, then you need to use an appropriate format i.e. XML. Otherwise, a simple text file is usually good enough -- at the lower levels the information is largely unstructured, so you might find dumps of arrays, stack dumps, etc. Provided you can correlated back to more structured logs at higher levels, things should be okay.

Q: If using files, do you use rolling logs or just a single file? How do you make the logs available for people to consume?

A: For files, generally you want rolling log files from a manageability point of view (with System.Diagnostics simply use VisualBasic.Logging.FileLogTraceListener).

Availability again depends on the system. If you are only talking about files then for a server/service, rolling files can just be accessed when necessary. (Windows Event Log or Database Application Logs would have their own access mechanisms).

If you don't have easy access to the file system, then debug tracing to a database may be easier. [i.e. implement a database TraceListener].

One interesting solution I saw for a Windows GUI application was that it logged very detailed tracing information to a "flight recorder" whilst running and then when you shut it down if it had no problems then it simply deleted the file.

If, however it crashed or encountered a problem then the file was not deleted. Either if it catches the error, or the next time it runs it will notice the file, and then it can take action, e.g. compress it (e.g. 7zip) and email it or otherwise make available.

Many systems these days incorporate automated reporting of failures to a central server (after checking with users, e.g. for privacy reasons).


Viewing

Q: What tools to you use for viewing the logs?

A: If you have multiple logs for different reasons then you will use multiple viewers.

Notepad/vi/Notepad++ or any other text editor is the basic for plain text logs.

If you have complex operations, e.g. activities with transfers, then you would, obviously, use a specialized tool like the Service Trace Viewer. (But if you don't need it, then a text editor is easier).

As I generally log high level information to the Windows Event Log, then it provides a quick way to get an overview, in a structured manner (look for the pretty error/warning icons). You only need to start hunting through text files if there is not enough in the log, although at least the log gives you a starting point. (At this point, making sure your logs have co-ordinated entires becomes useful).

Generally the Windows Event Log also makes these significant events available to monitoring tools like MOM or OpenView.

Others --

If you log to a Database it can be easy to filter and sort informatio (e.g. zoom in on a particular activity id. (With text files you can use Grep/PowerShell or similar to filter on the partiular GUID you want)

MS Excel (or another spreadsheet program). This can be useful for analysing structured or semi-structured information if you can import it with the right delimiters so that different values go in different columns.

When running a service in debug/test I usually host it in a console application for simplicity I find a colored console logger useful (e.g. red for errors, yellow for warnings, etc). You need to implement a custom trace listener.

Note that the framework does not include a colored console logger or a database logger so, right now, you would need to write these if you need them (it's not too hard).

It really annoys me that several frameworks (log4net, EntLib, etc) have wasted time re-inventing the wheel and re-implemented basic logging, filtering, and logging to text files, the Windows Event Log, and XML files, each in their own different way (log statements are different in each); each has then implemented their own version of, for example, a database logger, when most of that already existed and all that was needed was a couple more trace listeners for System.Diagnostics. Talk about a big waste of duplicate effort.

Q: If you are building an ASP.NET solution, do you also use ASP.NET Health Monitoring? Do you include trace output in the health monitor events? What about Trace.axd?

These things can be turned on/off as needed. I find Trace.axd quite useful for debugging how a server responds to certain things, but it's not generally useful in a heavily used environment or for long term tracing.

Q: What about custom performance counters?

For a professional application, especially a server/service, I expect to see it fully instrumented with both Performance Monitor counters and logging to the Windows Event Log. These are the standard tools in Windows and should be used.

You need to make sure you include installers for the performance counters and event logs that you use; these should be created at installation time (when installing as administrator). When your application is running normally it should not need have administration privileges (and so won't be able to create missing logs).

This is a good reason to practice developing as a non-administrator (have a separate admin account for when you need to install services, etc). If writing to the Event Log, .NET will automatically create a missing log the first time you write to it; if you develop as a non-admin you will catch this early and avoid a nasty surprise when a customer installs your system and then can't use it because they aren't running as administrator.

这篇关于记录最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆