例外をキャッチして Windows ログ ファイルに記録したいと考えています。Windows ログを開いて書き込むにはどうすればよいですか?
5 に答える
Enterprise Libraryの使用を検討することもできます。最初は複雑に見えますが、1 時間か 2 時間プレイすれば十分に効果があります。構成は app.config に保存されるため、再コンパイルせずに変更できます。これは、構成が異なるテスト サーバーとライブ サーバーに同じコードがある場合に非常に便利です。コードを大量に使わなくても、かなり多くのことができます。
良い点の 1 つは、例外が自動的にログに記録されるように例外ポリシーを定義できることです。使用できるコードを次に示します (私は EntLib 4.1 を使用しています)。
try
{
//This would be where your exception might be thrown. I'm doing it on
//purpose so you can see it work
throw new ArgumentNullException("param1");
}
catch (Exception ex)
{
if (ExceptionPolicy.HandleException(ex, "ExPol1")) throw;
}
ExPol1 で定義されている場合、catch ブロックの行は例外を再スローします。ExPol1 が再スロー用に構成されている場合、ExceptionPolicy.HandleException は true を返します。そうでない場合は false を返します。
残りは構成で定義します。XML はかなりひどいものに見えますが (いつもそうではありません)、Enterprise Library Configuration エディターを使用してこれを作成します。完全を期すために提供しているだけです。
このファイルの loggingConfiguration セクションでは、
- ログ: ローリング テキスト ログ ファイル (組み込みの Windows イベント ログ、SQL テーブル、電子メール、msmq などを使用できます)、
- パラメータがログに書き込まれる方法を管理するテキスト フォーマッタ (すべてを 1 行に書き込むように設定することもあれば、複数行にまたがるように設定することもあります)、
- 単一のカテゴリ「一般」
- config/entlib 内のエラーをトラップして報告する特別なソース。これを行うことを強くお勧めします。
exceptionHandling セクションでは、定義します。
- 単一のポリシー: 「ExPo1」。タイプ ArgumentNullExceptions を処理し、postHandlingAction を None (つまり、再スローしない) に指定します。
- 一般カテゴリ (上記で定義) にログを記録するハンドラ
この例では行いませんが、ポリシーを使用して例外を別のタイプに置き換えることもできます。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>
<loggingConfiguration name="Logging Application Block" tracingEnabled="true"
defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
<listeners>
<add fileName="rolling.log" footer="" formatter="Text Formatter"
header="" rollFileExistsBehavior="Overwrite" rollInterval="None"
rollSizeKB="500" timeStampPattern="yyyy-MM-dd" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="Rolling Flat File Trace Listener" />
</listeners>
<formatters>
<add template="Timestamp: {timestamp}; Message: {message}; Category: {category}; Priority: {priority}; EventId: {eventid}; Severity: {severity}; Title:{title}; Machine: {machine}; Application Domain: {appDomain}; Process Id: {processId}; Process Name: {processName}; Win32 Thread Id: {win32ThreadId}; Thread Name: {threadName}; 
 Extended Properties: {dictionary({key} - {value})}"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Rolling Flat File Trace Listener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="Rolling Flat File Trace Listener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
<exceptionHandling>
<exceptionPolicies>
<add name="ExPol1">
<exceptionTypes>
<add type="System.ArgumentNullException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="None" name="ArgumentNullException">
<exceptionHandlers>
<add logCategory="General" eventId="100" severity="Error" title="Enterprise Library Exception Handling"
formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
priority="0" useDefaultLogger="false" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="Logging Handler" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>
</configuration>
これらの記事では、発生する可能性がある未処理の例外を自動的にログに記録する方法について説明します。
VB.NET: http://visualbasic.about.com/od/usingvbnet/a/logging.htm