• Avalanche.Core
Search Results for

    Show / Hide Table of Contents
    • Avalanche.Accessor
      • Introduction
      • IAccessor
        • IAccessor
        • IListAccessor
        • IMapAccessor
        • IRecordAccessor
        • IContentAccessor
        • IOneOfAccessor
        • IAnyAccessor
      • .Net
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • Protobuf
        • Introduction
      • Articles
        • Dependency Injection
        • AccessorMessages
    • Avalanche.Binding
      • Introduction
    • Avalanche.Configuration
      • Introduction
      • Configuration Binding
      • ConfigurationExtensions
      • MemoryConfiguration
      • PrintTree
      • Saving IOptions
      • Yaml
    • Avalanche.Converter
      • Introduction
      • EnumConverter
      • Func<,>
      • HexConverter
      • PrimitiveConverter
      • StringConverter
    • Avalanche.Core
      • License
    • Avalanche.DataType
      • Introduction
      • DataType
        • IDataType
        • IListType
        • IMapType
        • IRecordType
        • IFieldType
        • IOneOfType
        • IAnyType
        • IStringType
        • IValueType
        • IIntegerType
        • IEnumerationType
        • IRealType
      • .Net
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • Enum
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • Protobuf
        • Introduction
      • Articles
        • DataTypeRequest
        • PrintTree
        • DataTypeMessages
    • Avalanche.Emit
      • Introduction
      • TypeBuilder
      • ConstructorBuilder
      • MethodBuilder
      • PropertyBuilder
      • FieldBuilder
      • Emit
      • Utilities
    • Avalanche.FileSystem
      • Introduction
      • Abstractions
        • IFileSystem
          • IFileSystemBrowse
          • IFileSystemCreateDirectory
          • IFileSystemDelete
          • IFileSystemFileAttribute
          • IFileSystemMount
          • IFileSystemMove
          • IFileSystemObserve
          • IFileSystemOpen
        • IEvent
        • IEntry
        • IOption
        • IToken
      • FileSystem
      • VirtualFileSystem
      • MemoryFileSystem
      • EmbeddedFileSystem
      • HttpFileSystem
      • Decoration
      • IFileProvider
      • Events
      • Utilities
        • Dispose
        • File Scanner
        • Visit Tree
        • File Operation
        • FilterEnumerable
        • PollingFilterWatchToken
    • Avalanche.Identity
      • Introduction
      • Identity
      • IdentityParts
      • IdentityInterner
      • IdentityComparer
      • Print Tree
      • IdentityAccessors
        • Introduction
        • TypeName
    • Avalanche.Localization
      • Introduction
      • Localization
      • LocalizationFile
      • LocalizationFiles
      • LocalizationFileSystem
      • LocalizationFileFormat
      • LocalizationLine
      • LocalizationLines
      • TemplateFormat
      • CultureProvider
      • FallbackCultureProvider
      • ResourceManager
      • LocalizationError
      • Microsoft.Extensions
        • Introduction
        • DependencyInjection
        • FileProvider
        • Logging
        • ITextLocalizer
        • IFileLocalizer
        • Localization
      • Asp.Net
        • Introduction
        • Supplying localization
        • Inject to pages
        • Culture Assigned
        • Minimalistic Api
        • Diagnostics
      • Pluralization
        • Introduction
        • Multiple plural parameters
        • Custom PluralRules
        • Invariant Culture
        • Unit Prefix
        • IPluralRule
        • IPluralNumber
        • IPluralRules
        • CLDRs
        • Unicode.CLDR40
        • Unicode.CLDR41
        • Unicode.CLDR42
      • Articles
        • Alphabet localization
        • Benchmarks
        • Caching
        • Class Library
        • Demo
        • Diagnostics
        • Embedded resources
        • Emplacement
        • File localization
        • Text localization
        • Printing templates
    • Avalanche.Message
      • Introduction
      • IMessage
      • IMessageProvider
      • IMessageDescription
      • IMessageDescriptions
      • MessageLevel
      • Message printing
      • Messages and Exceptions
      • Microsoft.Extensions
        • DependencyInjection
      • Articles
        • Aggregate Messages
        • Localization
        • Logging
        • Validation
    • Avalanche.Options
      • Introduction
      • OptionsExtensions
      • OptionsMonitorCast
    • Avalanche.Service
      • Introduction
      • Service
        • Introduction
        • IService
        • IServiceDisposable
        • IServiceDecoration
        • IServiceCast
        • IServiceObservable
        • IServiceContainer
        • Construction
        • Query
        • CancellationToken
        • CachePolicy
        • Scope
      • Handler
        • Introduction
        • IHandler
        • IHandlerCast
        • IHandlerDecoration
        • IHandlerWithOrder
        • CancellationToken
        • Cyclicity
        • Delegates
        • Invokable
        • ExportAttribute
        • OrderAttribute
        • PrintTree
        • Recursion
      • Query
        • Introduction
        • IQuery
        • IQueryCast
        • IQueryDecoration
      • Entry
        • Introduction
        • IEntry
        • IEntryCast
        • IEntryDecoration
        • IEntryObservable
        • IEntryVisitable
        • EntryState
      • Request
        • Introduction
        • IRequest
        • IRequestFor
        • IRequestToBeCached
        • IRequestToBeDisposed
        • RequestAttribute
        • ContextParameterAttribute
        • Print Tree
      • Dependency Injection
        • Introduction
        • Asp.Net
        • ServiceRequest<T>
        • Decorating a service
        • Handler
        • CachePolicy
        • CancellationToken
        • QueryLogger
        • IHostBuilder
      • Examples
        • NodeCount
        • Expression
        • Mapper
      • Articles
        • Benchmarks
        • Error Handling
        • ServiceMessages
    • Avalanche.StatusCode
      • Introduction
      • HResult
        • Introduction
        • HResult.Facilities
        • BasicMessages
        • RpcMessages
        • DispatchMessages
        • StorageMessages
        • ItfMessages
        • Win32Messages
        • WindowsMessages
        • SspiMessages
        • CertMessages
        • MediaServerMessages
        • SetupApiMessages
        • ScardMessages
        • ComPlusMessages
        • ClrMessages
        • UserModeFilterManagerMessages
        • GraphicsMessages
        • TpmServicesMessages
        • TpmSoftwareMessages
        • PlaMessages
        • FveMessages
        • FwpMessages
        • NdisMessages
        • DltMessages
      • System
        • Introduction
        • AccessControlMessages
        • AggregateMessages
        • AppDomainMessages
        • ArgumentMessages
        • ArgumentNullMessages
        • ArgumentOutOfRangeMessages
        • ArithmeticMessages
        • ArrayMessages
        • AssemblyMessages
        • BadImageFormatMessages
        • CodeContractMessages
        • CodePageMessages
        • CollectionsMessages
        • CompilerServiceMessages
        • CryptographyMessages
        • CultureMessages
        • DiagnosticsMessages
        • EventSourceMessages
        • ExecutionEngineMessages
        • FormatMessages
        • HostProtectionMessages
        • IOMessages
        • IndexOutOfRangeMessages
        • InteropServiceMessages
        • InvalidCastMessages
        • InvalidOperationMessages
        • IsolatedStorageMessages
        • LazyMessages
        • MarshalerMessages
        • MemoryMessages
        • MiscellaneousMessages
        • NotImplementedMessages
        • NotSupportedMessages
        • ObjectDisposedMessages
        • OperationCanceledMessages
        • OverflowMessages
        • PlatformMessages
        • PolicyMessages
        • PrincipalMessages
        • ProgramMessages
        • ReferenceMessages
        • ReflectionMessages
        • RegionMessages
        • RemotingMessages
        • ResourcesMessages
        • SecurityMessages
        • SerializationMessages
        • StackMessages
        • TaskMessages
        • TextMessages
        • ThreadingMessages
        • TimeZoneMessages
        • TypeMessages
        • XmlMessages
      • HttpStatusCode
      • OpcUaStatusCode
    • Avalanche.Template
      • Introduction
      • TemplateFormats
      • ITemplatePrintable
      • ITemplateFormatPrintable
      • ITemplateText
      • ITemplateBreakdown
      • ITemplateFormat
      • ITemplateFormats
      • Extract Arguments
      • Emplacement
    • Avalanche.Tokenizer
      • Introduction
      • IToken
      • ITokenizer
      • Tokenizers
    • Avalanche.Utilities
      • Introduction
      • Collections
        • Tuples
        • StructList
        • ArrayList
        • BijectionMap
        • LocakableDictionary
        • LockableList
        • MapList
        • Pipe
        • RingQueue
        • EnumerableExtensions
        • TupleUtilities
        • ArrayUtilities
      • Comparers
        • IGraphComparer
        • IGraphComparable
        • AlphaNumericComparer
        • EnumerableComparer
        • EnumerableGraphComparer
        • ReferenceComparer
        • KeyValuePairComparer
        • DefaultComparerProvider
        • RecordComparer
      • Cloners
        • ICloner
        • IGraphCloner
        • IGraphCloneable
        • ListCloner
        • DictionaryCloner
        • FieldCloner
        • PassthroughCloner
        • RecordCloner
        • ClonerProvider
      • Dispose
        • IDisposeAttachable
        • IDisposeBelatable
      • Provider
        • Introduction
        • ProviderBase
        • Delegate
        • Pipe
        • Cache
        • ResultCapture
        • AsReadOnly
        • AsService
        • IProviderEvent
      • Record
        • IRecordDescription
        • IFieldDescription
        • IConstructorDescription
        • IConstructionDescription
        • IParameterDescription
        • IRecordProviders
        • RecordDelegates
          • RecordCreate
          • RecordClone
          • RecordCopy
          • IRecordDelegates
        • FieldDelegates
          • FieldRead
          • FieldWrite
          • RecreateWith
          • IFieldDelegates
      • Reflection
        • EnumDescription
      • String
        • IEscaper
        • UnicodeString
        • Hex
      • Miscellaneous
        • IIdGenerator
        • Permutation
        • IReadOnly
        • IUserDataContainer
        • ITreeNode
        • Void
    • Avalanche.Writer
      • Introduction
      • ConstantWriter
      • Context
      • ConvertWriter
      • DefaultConstructor
      • DelegateWriter
      • PassthroughWriter
      • Referer
      • TypeCast
      • Writer
      • WriterPipe
      • WriterMessages

    Introduction

    Avalanche.Message.Logging.dll contains extension methods for ILogger.

    .LogMessage(this logger, message) writes message to logger.

    // Create message
    IMessage message = SystemMessages.ArgumentNull.Generic.New("argumentName");
    // Log message
    logger.LogMessage(message);
    

    .LogTo(this message, logger) writes message to logger.

    // Create message
    IMessage message = SystemMessages.ArgumentNull.Generic.New("argumentName");
    // Log message
    message.LogTo(logger);
    

    Note that .SetSeverity(this message, level) assigns overriding log level to the message.

    SystemMessages.ArgumentNull.Generic.New("argumentName").SetSeverity(LogLevel.Critical).LogTo(logger);
    

    .LogTo(this message, logger, loglevel) and .LogMessage(this logger, message, loglevel) overload log level parameter.

    IMessage msg = SystemMessages.ArgumentNull.Generic.New("argumentName");
    logger.LogMessage(msg, LogLevel.Critical);
    msg.LogTo(logger, LogLevel.Critical);
    

    Full Example

    Full example
    using System.Collections;
    using System.Globalization;
    using Avalanche.Message;
    using Avalanche.Service;
    using Avalanche.StatusCode;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using Serilog;
    using Serilog.Core;
    using Serilog.Events;
    
    class logging_index
    {
        public static void Run()
        {
            {
                // Service collection
                IServiceCollection serviceCollection = new ServiceCollection();
                // Add logging
                InitializeLogging(serviceCollection);
                // Services
                using var service = Services.Create((ServiceHandlers.Instance, serviceCollection));
                // Create ILogger
                var logger = service.GetRequiredService<Microsoft.Extensions.Logging.ILogger<index>>();
                // <01>
                // Create message
                IMessage message = SystemMessages.ArgumentNull.Generic.New("argumentName");
                // Log message
                logger.LogMessage(message);
                // </01>
            }
            {
                // Service collection
                IServiceCollection serviceCollection = new ServiceCollection();
                // Add logging
                InitializeLogging(serviceCollection);
                // Services
                using var service = Services.Create((ServiceHandlers.Instance, serviceCollection));
                // Create ILogger
                var logger = service.GetRequiredService<Microsoft.Extensions.Logging.ILogger<index>>();
                // <02>
                // Create message
                IMessage message = SystemMessages.ArgumentNull.Generic.New("argumentName");
                // Log message
                message.LogTo(logger);
                // </02>
            }
            {
                // Service collection
                IServiceCollection serviceCollection = new ServiceCollection();
                // Add logging
                InitializeLogging(serviceCollection);
                // Services
                using var service = Services.Create((ServiceHandlers.Instance, serviceCollection));
                // Create ILogger
                var logger = service.GetRequiredService<Microsoft.Extensions.Logging.ILogger<index>>();
                // <03>
                SystemMessages.ArgumentNull.Generic.New("argumentName").SetSeverity(LogLevel.Critical).LogTo(logger);
                // </03>
            }
            {
                // Service collection
                IServiceCollection serviceCollection = new ServiceCollection();
                // Add logging
                InitializeLogging(serviceCollection);
                // Services
                using var service = Services.Create((ServiceHandlers.Instance, serviceCollection));
                // Create ILogger
                var logger = service.GetRequiredService<Microsoft.Extensions.Logging.ILogger<index>>();
                // <04>
                IMessage msg = SystemMessages.ArgumentNull.Generic.New("argumentName");
                logger.LogMessage(msg, LogLevel.Critical);
                msg.LogTo(logger, LogLevel.Critical);
                // </04>
            }        
        }
    
        static IServiceCollection InitializeLogging(IServiceCollection serviceCollection)
        {
            // Initial configuration
            MemoryConfiguration memConfig = new MemoryConfiguration()
                .Set("Logging:LogLevel:Default", "Debug")
                .Set("Serilog:WriteTo:0:Name", "Console")
                .Set("Serilog:WriteTo:0:Args:OutputTemplate", "[{EventIdHex} {Level:u1}] {Message:lj}{NewLine}{Exception}")
                .Set("Serilog:WriteTo:0:Args:RestrictedToMinimumLevel", "Verbose")
                .Set("Serilog:WriteTo:0:Args:Theme", "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console");
    
            // Read configuration
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .Add(memConfig)
                .Build();
    
            //
            var switchableLogger = new Serilog.SwitchableLogger();
            // Logging
            serviceCollection.AddLogging(loggingBuilder =>
                    loggingBuilder
    #if DEBUG
                        .SetMinimumLevel(LogLevel.Trace)
    #else
                        .SetMinimumLevel(LogLevel.Information)
    #endif
                        .AddSerilog(switchableLogger, true)
                        .AddSerilogConfigurationLoader(configuration, switchableLogger,
                            c => new Serilog.LoggerConfiguration()
    #if DEBUG
                                    .MinimumLevel.Verbose()
    #else
                                    .MinimumLevel.Information()
    #endif
                                    .Enrich.With(new EventIdEnricher())
                                .ReadFrom.Configuration(configuration)
                                .CreateLogger())
                    );
            //
            return serviceCollection;
        }
    
        /// <summary>Memory configuration</summary>
        public class MemoryConfiguration : ConfigurationProvider, IEnumerable<KeyValuePair<string, string>>, IConfigurationSource
        {
            /// <summary>Expose inner configuration data</summary>
            public new IDictionary<String, String> Data => base.Data;
            /// <summary>Configuration data</summary>
            public string this[string key] { get => base.Data[key]; set => base.Data[key] = value; }
    
            /// <summary>Create memory configuration</summary>
            public MemoryConfiguration() : base() { }
    
            /// <summary>Assign <paramref name="value"/> to <paramref name="key"/></summary>
            public new MemoryConfiguration Set(string key, string value) { base.Data[key] = value; return this; }
            /// <summary>Build configuration provider.</summary>
            public IConfigurationProvider Build(IConfigurationBuilder builder) => this;
            /// <summary>Enumerate</summary>
            public IEnumerator<KeyValuePair<string, string>> GetEnumerator() => Data.GetEnumerator();
            /// <summary>Enumerate</summary>
            IEnumerator IEnumerable.GetEnumerator() => Data.GetEnumerator();
        }
    
        /// <summary>Serilog enricher that reduces "EventId" to its "id" field.</summary>
        public class EventIdEnricher : ILogEventEnricher
        {
            /// <summary>Reduce to EventId.id</summary>
            public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
            {
                // Get properties
                if (!logEvent.Properties.TryGetValue("EventId", out LogEventPropertyValue? eventIdStructure)) return;
                // Not structure field
                if (eventIdStructure is not StructureValue structureValue || structureValue.Properties == null) return;
                // Get list
                IReadOnlyList<LogEventProperty> list = structureValue.Properties;
                // Process each
                for (int i = 0; i < list.Count; i++)
                {
                    // Get property
                    LogEventProperty logEventProperty = list[i];
                    // Not id
                    if (logEventProperty.Name != "Id") continue;
                    // New property
                    LogEventProperty eventId = propertyFactory.CreateProperty("EventId", logEventProperty.Value);
                    // Add as new key
                    logEvent.AddOrUpdateProperty(eventId);
                    // Print as hex
                    string hex = logEventProperty.Value.ToString("X8", CultureInfo.InvariantCulture);
                    // New property
                    LogEventProperty eventIdHex = propertyFactory.CreateProperty("EventIdHex", hex);
                    // Add as new key
                    logEvent.AddOrUpdateProperty(eventIdHex);
                    // Completed
                    return;
                }
            }
        }
    }
    
    In This Article
    Back to top Copyright © Toni Kalajainen