// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Shared.Diagnostics; namespace Microsoft.Extensions.AI; /// Provides extensions for configuring instances. public static class LoggingChatClientBuilderExtensions { /// Adds logging to the chat client pipeline. /// The . /// /// An optional used to create a logger with which logging should be performed. /// If not supplied, a required instance will be resolved from the service provider. /// /// An optional callback that can be used to configure the instance. /// The . /// is . /// /// /// When the employed enables , the contents of /// chat messages and options are logged. These messages and options may contain sensitive application data. /// is disabled by default and should never be enabled in a production environment. /// Messages and options are not logged at other logging levels. /// /// public static ChatClientBuilder UseLogging( this ChatClientBuilder builder, ILoggerFactory? loggerFactory = null, Action? configure = null) { _ = Throw.IfNull(builder); return builder.Use((innerClient, services) => { loggerFactory ??= services.GetRequiredService(); // If the factory we resolve is for the null logger, the LoggingChatClient will end up // being an expensive nop, so skip adding it and just return the inner client. if (loggerFactory == NullLoggerFactory.Instance) { return innerClient; } var chatClient = new LoggingChatClient(innerClient, loggerFactory.CreateLogger(typeof(LoggingChatClient))); configure?.Invoke(chatClient); return chatClient; }); } }