Thursday, July 16, 2015

Write to Event Log: Examples in C#, CMD, SQL, PS1, WMI

Couple ways to log to event log, then we can use simple filtering and alerts in EvtViewer to create a quick and dirty notification sub-system in case we dont have time to implement notifications in an app or we are using an existing app such as a COTS product, See here

Log to Event Log using:

CMD 
using eventcreate:
eventcreate /ID 755 /L APPLICATION /T INFORMATION  /SO BACKUP /D "My first log"

C# System.Diagnostics
 System.Diagnostics.EventLog.WriteEntry(source,
                        message,
                        ConvertTraceType(type),
                        eventId);

c# MS App Blocks
Logger.Write(message, LogSources.CheckSource(source), Priority.Normal, eventId, type, title, dictionary);

Logger.Write(ex, LogSources.DefaultSource(), Priority.High,
                    eventid, TraceEventType.Error, title , dictionary);

PS check source, create 
if ([System.Diagnostics.EventLog]::SourceExists($mysource) -eq $false) {
    [System.Diagnostics.EventLog]::CreateEventSource($mysource, "Application")

}

PS  log
Write-EventLog -LogName "Application" -Source $mysource -EntryType Information -EventID 100 -Message "Start logging!"
Write-EventLog –LogName Application –Source “My Script” –EntryType Information –EventID 1
 –Message “This is a test message.”

WMI
strEventDescription = "Payroll application could not be installed on " _ 
    & objNetwork.UserDomain & "\" & objNetwork.ComputerName _ 
        & " by user " & objNetwork.UserName & _
            ". Free space on each drive is: " & strDriveSpace
objShell.LogEvent EVENT_FAILED, strEventDescription
SQL (T-SQL)
  DECLARE @msg VARCHAR(100)      SELECT @msg = ERROR_Message()
    RAISERROR(@msg, 11, 1) WITH LOG
-- OR
USE master;
EXEC xp_logevent 60000, @@MESSAGE, informational
C# Ent Logging Detail:
public void EntLoggingTest03()
        {
            try
            {
                LogEntry entry = new LogEntry();
                //entry.ActivityIdString = "ActivityIdString";
                entry.AppDomainName = "AppDomainName";
                //entry.Categories.Add("DTech Data Services NOC Services");
                entry.Categories.Add(SOURCE);
                //entry.ErrorMessages = "ErrorMessages";
                entry.EventId = (int)LogEventID.FileRouterEventID.FileRouterError;
                Dictionary<stringobject> dictionary = new Dictionary<stringobject>();
                dictionary.Add("ZipFile""1.zip");
                dictionary.Add("ZipURI"@"C:\Tamepo");
                entry.ExtendedProperties = dictionary;
                //entry.LoggedSeverity = "LoggedSeverity";
                entry.MachineName = "Me";
                entry.Message = "a msg";
                entry.Priority = 1;
 
                entry.ProcessName = "DTech.Util.Data.Test?";
                entry.Severity = TraceEventType.Warning;
 
                Logger.Write(entry);
 
                //                throw new ArgumentException("InsertEventLogErrorTest00 EXCEPTION");
            }
            catch (Exception ex)
            {
 
                handleException(ex);
            }
            Assert.IsTrue(true);
        }
How to use EntLib (old directions)
 /// 1) Download April or May 2007 Enterprise Lib : 
    ///     URL : http://msdn.microsoft.com/en-us/library/aa480453.aspx

    ///     
    /// Steps to use Ent Lib Logging!
    /// 1) Open your or add an app.config to your app.
    /// 2) Add Reference to 
    ///     Microsoft.Practices.EnterpriseLibrary.Logging (C:\Program Files\Microsoft Enterprise Library 3.0 - April 2007\Bin\)
    ///     Microsoft.Practices.EnterpriseLibrary.Common.dll: (C:\Program Files\Microsoft Enterprise Library 3.0 - April 2007\Bin\)
    ///     Microsoft.Practices.EnterpriseLibrary.Data.dll: C:\Program Files\Microsoft Enterprise Library 3.0 - April 2007\Bin\
    /// 3) Open your App.Config and the App.Config from this app (DTech.Logging.Test.config)
    /// 4) Copy the following from this app's App.config to your App.config
    ///         - /configuration/configSections 
    ///         - /configuration/loggingConfiguration
    ///  5) Open the Ent Lib Config Tool: EntLibConfig.exe : "C:\Program Files\Microsoft Enterprise Library 3.0 - April 2007\Bin\
    ///         - Open your app.config and go to Logginng Application Block|Category Sources

    ///  6) You are now done and your app is ready to use the Entreprise Library Logging Block!
    ///  
    /// Why should you use Ent Lib for Logging?
    /// 1) Saves time
    /// 2) Easy to use
    /// 3) Change logging destination without change to code
    /// 4) Only need to reference 3 dll's to work
    /// 5) Log to DB and Event log with ease
    /// 6) Consistent and stable design
    /// 7) Your app will have an automatic UI to manage your config file.
    /// 8) Administration of Logging Destination via Rich UI, no need to change code
    /// 9) Extensible

No comments:

Post a Comment