Imports Mercury.Mobile

Namespace Logging

    ''' <summary>
    ''' A set of methods for initializing the correct logging framework and retrieving the context.
    ''' </summary>
    ''' <remarks></remarks>
    Public NotInheritable Class Log

        Private Shared _registeredLogNames As IList(Of String) = New List(Of String)()
        Private Shared _currentType As Type = GetType(NullLog)
        Private Shared _current As ILog

        ''' <summary>
        ''' Returns a list of registered log names. If any logs are registered, Log.GetLogger() 
        ''' will only create and return logs for the registered log names.
        ''' </summary>
        Public Shared ReadOnly Property RegisteredLogNames() As IList(Of String)
            Get
                Return _registeredLogNames
            End Get
        End Property

        ''' <summary>
        ''' Initializes the logging framework with the specified logger type.
        ''' </summary>
        ''' <typeparam name="T">The type of the logger to use.</typeparam>
        ''' <remarks></remarks>
        Public Shared Sub InitializeWith(Of T As {ILog, New})()
            _currentType = GetType(T)
        End Sub

        ''' <summary>
        ''' Initializes the logging framework with the specified logger instance. If 
        ''' the log instance is set all logging calls will be routed to this logger.
        ''' </summary>
        ''' <param name="logger">The ILog instance to use for logging.</param>
        ''' <remarks></remarks>
        Public Shared Sub InitializeWith(ByVal logger As ILog)
            If logger Is Nothing Then _
                Throw New ArgumentNullException("logger")
            _currentType = logger.GetType()
            _current = logger
        End Sub

        ''' <summary>
        ''' Returns a logger initialized with the specified log name.
        ''' </summary>
        ''' <param name="logName">The name of the logger.</param>
        ''' <returns>A logger initialized with the specified log name or the default logger instance.</returns>
        ''' <remarks></remarks>
        Public Shared Function GetLogger(ByVal logName As String) As ILog
            If RegisteredLogNames.Count > 0 AndAlso Not (RegisteredLogNames.Contains(logName)) Then _
                Return Nothing
            Dim logger = _current
            If _current Is Nothing Then
                logger = TryCast(Activator2.CreateInstance(_currentType), ILog)
                If logger IsNot Nothing Then _
                    logger.Initialize(logName)
            End If
            Return logger
        End Function

    End Class

End Namespace