Skip to content

Instantly share code, notes, and snippets.

@huguogang
Created July 8, 2010 05:22
Show Gist options
  • Save huguogang/467670 to your computer and use it in GitHub Desktop.
Save huguogang/467670 to your computer and use it in GitHub Desktop.
SQL Fixed Width Number Formatting
RIGHT('00000' + CAST(myNumber AS VARCHAR), 5)
@everdan
Copy link

everdan commented Sep 14, 2012

using System;
using System.Diagnostics;
using log4net.Appender;
using log4net.Repository.Hierarchy;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using log4net.Core;

namespace Log4NetRole
{
///

/// Represents the appender for Azure environment used by log4net logging framework
/// </summary>


public class AzureAppender : AppenderSkeleton
{
    private const string connectionStringKey = "Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString";
    private const string levelKey = "Diagnostics.Level";
    private const string layoutKey = "Diagnostics.Layout";
    private const string scheduledTransferPeriodKey = "Diagnostics.ScheduledTransferPeriod";
    private const string eventLogsKey = "Diagnostics.EventLogs";
    /// <summary>
    /// Get or set the scheduled transfer period
    /// </summary>
    public int ScheduledTransferPeriod { get; set; }

    /// <summary>
    /// Get or set the logging level
    /// </summary>
    public string Level { get; set; }

    /// <summary>
    /// Add the loggingEvent to the listener
    /// </summary>
    /// <param name="loggingEvent">Logging Event</param>
    protected override void Append(LoggingEvent loggingEvent)
    {
        var logString = RenderLoggingEvent(loggingEvent);

        switch(loggingEvent.Level.Name)
        {
            case "ERROR":
                System.Diagnostics.Trace.TraceError(logString);
                break;
            case "WARN":
                System.Diagnostics.Trace.TraceWarning(logString);
                break;
            case "INFO":
                System.Diagnostics.Trace.TraceInformation(logString);
                break;
            case "ALL":
                System.Diagnostics.Trace.Write(logString);
                break;
             case "DEBUG":
                System.Diagnostics.Trace.Write(logString);
                break;
             default:
                System.Diagnostics.Trace.Write(logString);
                break;

        }
    }


    /// <summary>
    /// Configure the options
    /// </summary>
    public override void ActivateOptions()
    {
        ScheduledTransferPeriod = GetScheduledTransferPeriod();
        Layout = new log4net.Layout.PatternLayout(GetLayout());
        Level = GetLevel();

        ConfigureThreshold();

        base.ActivateOptions();           

        ConfigureAzureDiagnostics();
    }

    /// <summary>
    /// Configure the options for the Azure webrole
    /// </summary>
    /// <param name="webRole">True for webrole</param>
    public void ActivateOptions(bool webRole)
    {
        if (webRole)
        {
            ScheduledTransferPeriod = GetScheduledTransferPeriod();
            Layout = new log4net.Layout.PatternLayout(GetLayout());
            Level = GetLevel();

            ConfigureThreshold();

            base.ActivateOptions();

            var traceListener = new DiagnosticMonitorTraceListener();
            Trace.Listeners.Add(traceListener);
        }
        else
            ActivateOptions();
    }

    /// <summary>
    /// Configure threshold id
    /// </summary>
    private void ConfigureThreshold()
    {

        var rootRepository = (Hierarchy)log4net.LogManager.GetLoggerRepository();
        Threshold = rootRepository.LevelMap[Level];
    }

    /// <summary>
    /// Configure Azure diagnostics information
    /// </summary>
    private void ConfigureAzureDiagnostics()
    {
        var traceListener = new DiagnosticMonitorTraceListener();
        Trace.Listeners.Add(traceListener);

        var dmc = DiagnosticMonitor.GetDefaultInitialConfiguration();

        //set threshold to verbose, what gets logged is controled by the log4net level
        dmc.Logs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;

        ScheduleTransfer(dmc);

        ConfigureWindowsEventLogsToBeTransferred(dmc);

        DiagnosticMonitor.Start(connectionStringKey, dmc);
    }

    /// <summary>
    /// Configure scheduled tranfer period for Azure diagnostics information
    /// </summary>
    /// <param name="dmc">Diagnostice Monitor configuration</param>
    private void ScheduleTransfer(DiagnosticMonitorConfiguration dmc)
    {
        var transferPeriod = TimeSpan.FromMinutes(ScheduledTransferPeriod);
        dmc.Logs.ScheduledTransferPeriod = transferPeriod;
        dmc.WindowsEventLog.ScheduledTransferPeriod = transferPeriod;
    }

    /// <summary>
    /// Configures the  windows event logs to be collected and transfered
    /// </summary>
    /// <param name="dmc">Diagnostice Monitor configuration</param>
    private static void ConfigureWindowsEventLogsToBeTransferred(DiagnosticMonitorConfiguration dmc)
    {
        var eventLogs = GetEventLogs().Split(';');
        foreach (var log in eventLogs)
        {
            dmc.WindowsEventLog.DataSources.Add(log);
        }
    }

    /// <summary>
    /// Get the level of logging based on the configuration settings
    /// </summary>
    /// <returns>Logging level as configured</returns>
    private static string GetLevel()
    {
        string value = CloudConfigurationManager.GetSetting(levelKey);

        if (string.IsNullOrWhiteSpace(value))
            value = "Error";
        return value;
    }

    /// <summary>
    /// Get the layout for the log inforamtion
    /// </summary>
    /// <returns>Log message layout</returns>
    private static string GetLayout()
    {
        string value = CloudConfigurationManager.GetSetting(layoutKey);

        if(string.IsNullOrWhiteSpace(value))
            value = "%d [%t] %-5p %c [%x] <%X{auth}> - %m%n";

        return value;
    }

    /// <summary>
    /// Get the schduled transfer period of log entries to persistant media
    /// </summary>
    /// <returns>Period to transfer log entries</returns>
    private static int GetScheduledTransferPeriod()
    {
        int period = 1;

        int.TryParse(CloudConfigurationManager.GetSetting(scheduledTransferPeriodKey), out period);

        return period;
    }

    /// <summary>
    /// Get the event logs to be collected
    /// </summary>
    /// <returns>Event logs root to be collected</returns>
    private static string GetEventLogs()
    {
        string value = CloudConfigurationManager.GetSetting(eventLogsKey);

        if(string.IsNullOrWhiteSpace(value))
            value = "Application!*;System!*";

        return value;
    }

}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment