創建自定義的事件接收器-Semantic Logging

創建自定義的事件接收器-Semantic Logging

來自專欄軟體應用大全

創建自定義的事件接收器

Semantic Logging Application Block提供了大量的事件接收器,如Rolling Flat File,SQL Database, 雲存儲接收器等。這些接收器都實現了IObservable<EventEntry>介面。

有時這些並不能很好的滿足客戶需求,這時就需要定製事件接收器,比如郵件接收器、簡訊接收器等。

下面介紹以下如何定製郵件接收器,在特定的事件發生時自動發送郵件給指定的客戶。

本文介紹了以下主題:

  • 創建自定義接收器
  • 在進程內使用自定義接收器

創建自定義接收器

要創建自定義接收器,必須實現IObservable<EventEntry>介面,該介面提供了3個函數:OnCompleted,OnError和OnExt

public interface IObserver<in T>{void OnCompleted();void OnError(Exception error);void OnNext(T value);}

下面的展示了如何創建自定義的Email接收器。

public sealed class EmailSink : IObserver<EventEntry>{private const string DefaultSubject = "Email Sink Extension";private IEventTextFormatter formatter;private MailAddress sender;private MailAddressCollection recipients = new MailAddressCollection();private string subject;private string host;private int port;private NetworkCredential credentials;public EmailSink(string host, int port,string recipients, string subject, string credentials,IEventTextFormatter formatter){this.formatter = formatter ?? new EventTextFormatter();this.host = host;this.port = GuardPort(port);this.credentials = CredentialManager.GetCredentials(credentials);this.sender = new MailAddress(this.credentials.UserName);this.recipients.Add(GuardRecipients(recipients));this.subject = subject ?? DefaultSubject;}public void OnNext(EventEntry entry){if (entry != null){using (var writer = new StringWriter()){this.formatter.WriteEvent(entry, writer);Post(writer.ToString());}}}public void OnCompleted() {}public void OnError(Exception error) {}private void Post(string body){using (var client = new SmtpClient(this.host, this.port){ Credentials = this.credentials, EnableSsl = true })using (var message = new MailMessage(this.sender, this.recipients[0]){ Body = body, Subject = this.subject }){for (int i = 1; i < this.recipients.Count; i++)message.CC.Add(this.recipients[i]);try{client.Send(message);}catch (SmtpException e){SemanticLoggingEventSource.Log.CustomSinkUnhandledFault("SMTP error sending email: " + e.Message);}catch (InvalidOperationException e){SemanticLoggingEventSource.Log.CustomSinkUnhandledFault("Configuration error sending email: " + e.Message);}catch (...){// additional exception handling code here.}}}private static int GuardPort(int port){if (port < 0)throw new ArgumentOutOfRangeException("port");return port;}private static string GuardRecipients(string recipients){if (recipients == null)throw new ArgumentNullException("recipients");if (string.IsNullOrWhiteSpace(recipients))throw new ArgumentException("The recipients cannot be empty", "recipients");return recipients;}}

並使用一個擴展函數來實例化監聽器,代碼如下

public static class EmailSinkExtensions{public static EventListener CreateListener(string host, int port,string recipients, string subject, string credentials,IEventTextFormatter formatter = null){var listener = new ObservableEventListener();listener.LogToEmail(host, port, recipients, subject, credentials, formatter);return listener;}public static SinkSubscription<EmailSink> LogToEmail(this IObservable<EventEntry> eventStream, string host, int port,string recipients, string subject, string credentials,IEventTextFormatter formatter = null){var sink = new EmailSink(host, port, recipients, subject, credentials, formatter);var subscription = eventStream.Subscribe(sink);return new SinkSubscription<EmailSink>(subscription, sink);}}

如何使用自定義接收器

private void ButtonBase_OnClick(object sender, RoutedEventArgs e){var listener = new ObservableEventListener();listener.LogToEmail("smtp.live.com", 25, "XXXX@163.com", "In Proc Sample", "etw");listener.EnableEvents(MyCompanyEventSource.Log,EventLevel.LogAlways, EventKeywords.All);MyCompanyEventSource.Log.Startup();}

推薦閱讀:

TAG:自定義 | 計算機視覺 |