Antonio "tdj"

(C'è sempre un modo migliore)
posts - 312, comments - 268, trackbacks - 17

My Links

News





Tag Cloud

Article Categories

Archives

Post Categories

Image Galleries

Articoli

Blogs

Controlli WinForm free

Guide

Siti vari

Sviluppo

Usare log4net per i log di LINQ

Il DataContext di LINQ prevede una proprietà Log di tipo TextWriter per fare il log delle operazioni eseguite. Utilizzando ormai log4net per i log mi sono creato un piccolo wrapper per utilizzarlo con LINQ:

 

   1:  Public Class LinqLogger
   2:      Inherits TextWriter
   3:   
   4:      Private _encoding As UnicodeEncoding
   5:      Private Log As ILog = LogManager.GetLogger(GetType(LinqLogger))
   6:      Private LogLevel As Level = Level.Debug
   7:   
   8:      Public Overrides ReadOnly Property Encoding() As System.Text.Encoding
   9:           Get
  10:              If _encoding Is Nothing Then
  11:                 _encoding = New UnicodeEncoding(False, False)
  12:              End If
  13:              Return _encoding
  14:           End Get
  15:       End Property
  16:   
  17:       Sub New()
  18:       End Sub
  19:   
  20:       Sub New(ByVal logLevel As Level)
  21:            Me.new(Nothing, logLevel)
  22:       End Sub
  23:   
  24:       Sub New(ByVal logger As ILog, ByVal logLevel As Level)
  25:           If logger IsNot Nothing Then
  26:               Me.Log = logger
  27:           End If
  28:           Me.LogLevel = logLevel
  29:       End Sub
  30:   
  31:       Public Overrides Sub Write(ByVal value As String)
  32:           Select Case Me.LogLevel
  33:               Case Level.Debug
  34:                   Log.Debug(value)
  35:               Case Level.Warn
  36:                   Log.Warn(value)
  37:               Case Level.Info
  38:                   Log.Info(value)
  39:               Case Level.Error
  40:                   Log.Error(value)
  41:               Case Level.Fatal
  42:                   Log.Fatal(value)
  43:            End Select
  44:       End Sub
  45:   
  46:       Public Overrides Sub Write(ByVal buffer() As Char, ByVal index As Integer, ByVal count As Integer)
  47:     Me.Write(New String(buffer, index, count))
  48:       End Sub
  49:  End Class

Alla classe viene passato sia il “level” del log che un eventuale Logger da utilizzare dopodichè viene fatto l’override della proprietà Encoding (8) e del metodo Write (31) che fisicamente usa l’appender di log4net per loggare.

Un esempio d’uso è questo:

MyDataContext.Log = New LinqLogger(Level.Debug)

oppure:

Dim log As ILog = LogManager.GetLogger(GetType(MyClass1))
MyDataContext.Log = New LinqLogger(log, Level.Debug)

Print | posted on sabato 21 febbraio 2009 00:10 | Filed Under [ .NET ]

Comments have been closed on this topic.

Powered by:
Powered By Subtext Powered By ASP.NET