Here are the examples of the csharp api Microsoft.Extensions.Logging.ILogger.IsEnabled(Microsoft.Extensions.Logging.LogLevel) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
96 Examples
19
Source : AppMetricsMiddlewareHealthChecksLoggerExtensions.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
public static void MiddlewareExecuted<TMiddleware>(this ILogger logger)
{
if (logger.IsEnabled(LogLevel.Trace))
{
logger.LogTrace(AppMetricsEventIds.Middleware.MiddlewareExecutedId, $"Executed App Metrics Health Middleware {typeof(TMiddleware).FullName}");
}
}
19
Source : AppMetricsMiddlewareHealthChecksLoggerExtensions.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
public static void MiddlewareExecuting<TMiddleware>(this ILogger logger)
{
if (logger.IsEnabled(LogLevel.Trace))
{
logger.LogTrace(AppMetricsEventIds.Middleware.MiddlewareExecutingId, $"Executing App Metrics Health Middleware {typeof(TMiddleware).FullName}");
}
}
19
Source : AppMetricsMiddlewareLoggerExtensions.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
public static void MiddlewareExecuted<TMiddleware>(this ILogger logger)
{
if (logger.IsEnabled(LogLevel.Trace))
{
logger.LogTrace(AppMetricsEventIds.Middleware.MiddlewareExecutedId, $"Executed App Metrics Middleware {typeof(TMiddleware).FullName}");
}
}
19
Source : AppMetricsMiddlewareLoggerExtensions.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
public static void MiddlewareExecuting<TMiddleware>(this ILogger logger)
{
if (logger.IsEnabled(LogLevel.Trace))
{
logger.LogTrace(AppMetricsEventIds.Middleware.MiddlewareExecutingId, $"Executing App Metrics Middleware {typeof(TMiddleware).FullName}");
}
}
19
Source : LoggingHttpMessageHandler.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public static void RequestEnd(ILogger logger, HttpResponseMessage response, TimeSpan duration)
{
_requestEnd(logger, duration.TotalMilliseconds, response.StatusCode, null);
if (logger.IsEnabled(LogLevel.Trace))
{
logger.Log(
LogLevel.Trace,
EventIds.ResponseHeader,
new HttpHeadersLogValue(HttpHeadersLogValue.Kind.Response, response.Headers, response.Content?.Headers),
null,
(state, ex) => state.ToString());
}
}
19
Source : LoggingHttpMessageHandler.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public static void RequestStart(ILogger logger, HttpRequestMessage request)
{
_requestStart(logger, request.Method, request.RequestUri, null);
if (logger.IsEnabled(LogLevel.Trace))
{
logger.Log(
LogLevel.Trace,
EventIds.RequestHeader,
new HttpHeadersLogValue(HttpHeadersLogValue.Kind.Request, request.Headers, request.Content?.Headers),
null,
(state, ex) => state.ToString());
}
}
19
Source : LoggingScopeHttpMessageHandler.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public static void RequestPipelineStart(ILogger logger, HttpRequestMessage request)
{
_requestPipelineStart(logger, request.Method, request.RequestUri, null);
if (logger.IsEnabled(LogLevel.Trace))
{
logger.Log(
LogLevel.Trace,
EventIds.RequestHeader,
new HttpHeadersLogValue(HttpHeadersLogValue.Kind.Request, request.Headers, request.Content?.Headers),
null,
(state, ex) => state.ToString());
}
}
19
Source : LoggingScopeHttpMessageHandler.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public static void RequestPipelineEnd(ILogger logger, HttpResponseMessage response, TimeSpan duration)
{
_requestPipelineEnd(logger, duration.TotalMilliseconds, response.StatusCode, null);
if (logger.IsEnabled(LogLevel.Trace))
{
logger.Log(
LogLevel.Trace,
EventIds.ResponseHeader,
new HttpHeadersLogValue(HttpHeadersLogValue.Kind.Response, response.Headers, response.Content?.Headers),
null,
(state, ex) => state.ToString());
}
}
19
Source : RazorDiagnosticsPublisher.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
internal async Task PublishDiagnosticsAsync(DoreplacedentSnapshot doreplacedent)
{
var result = await doreplacedent.GetGeneratedOutputAsync();
var diagnostics = result.GetCSharpDoreplacedent().Diagnostics;
lock (_publishedDiagnostics)
{
if (_publishedDiagnostics.TryGetValue(doreplacedent.FilePath, out var previousDiagnostics) &&
diagnostics.SequenceEqual(previousDiagnostics))
{
// Diagnostics are the same as last publish
return;
}
_publishedDiagnostics[doreplacedent.FilePath] = diagnostics;
}
if (!doreplacedent.TryGetText(out var sourceText))
{
Debug.Fail("Doreplacedent source text should already be available.");
}
var convertedDiagnostics = diagnostics.Select(razorDiagnostic => RazorDiagnosticConverter.Convert(razorDiagnostic, sourceText));
PublishDiagnosticsForFilePath(doreplacedent.FilePath, convertedDiagnostics);
if (_logger.IsEnabled(LogLevel.Trace))
{
var diagnosticString = string.Join(", ", diagnostics.Select(diagnostic => diagnostic.Id));
_logger.LogTrace($"Publishing diagnostics for doreplacedent '{doreplacedent.FilePath}': {diagnosticString}");
}
}
19
Source : App.cs
with MIT License
from Azure
with MIT License
from Azure
[System.Diagnostics.Codereplacedysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Converting to return code for command line.")]
public async Task<int> RunAsync(CancellationToken token)
{
// Merge configuration
_options.MergeConfig();
// Set defaults if no value set in config or command line
_options.ApplyDefaults();
// Validate options
if (!ValidateOptions(_options))
{
return await Task.FromResult(ReturnCodeConstants.ArgsError).ConfigureAwait(false);
}
// Set logging level
SetLogLevel(_options);
// Set options
SetOptions(_options);
// Print options
_options.PrintOptions();
// The model and stage runners may contain types that are not loaded into the default replacedembly load context
// because they are types used by a plugin that populated the model. Try and resolve any unresolved replacedemblies
// with the plugin host instead when the runner is executed. This particularly affects XmlSerializer where
// it generates a custom serialization replacedembly that is always loaded into the default replacedembly load context.
replacedemblyLoadContext.Default.Resolving += ResolvereplacedemblyHandler;
try
{
// Build runner
var runner = BuildRunner();
if (runner != null)
{
try
{
// Run app
await runner.RunAsync(token).ConfigureAwait(false);
// Save model (if required)
SaveModel(runner);
// Print out execution stats
PrintExecutionStats(runner.RunState);
}
catch (OperationCanceledException)
{
_logger.LogInformation(InformationMessages.RunnerCancelled);
return await Task.FromResult(ReturnCodeConstants.Cancelled).ConfigureAwait(false);
}
catch (RunnerException e)
{
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogError(e, ErrorMessages.FullExceptionDetails);
}
return await Task.FromResult(ReturnCodeConstants.AppError).ConfigureAwait(false);
}
catch (Exception e)
{
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogError(e, ErrorMessages.FullExceptionDetails);
}
return await Task.FromResult(ReturnCodeConstants.AppError).ConfigureAwait(false);
}
return await Task.FromResult(ReturnCodeConstants.Success).ConfigureAwait(false);
}
else
{
// Nothing to run
return await Task.FromResult(ReturnCodeConstants.Success).ConfigureAwait(false);
}
}
catch (Exception e)
{
_logger.LogError(ErrorMessages.FailedBuildingRunner, e.Message);
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogError(e, ErrorMessages.FullExceptionDetails);
}
return await Task.FromResult(ReturnCodeConstants.AppError).ConfigureAwait(false);
}
finally
{
// Unhook from event
replacedemblyLoadContext.Default.Resolving -= ResolvereplacedemblyHandler;
}
}
19
Source : App.cs
with MIT License
from Azure
with MIT License
from Azure
private IApplicationModel LoadModel()
{
// Should we save model?
if (_options.Options.Model != null)
{
_logger.LogDebug(TraceMessages.LoadingModel, _options.Options.Model.FullName);
// Read model file content
var json = File.ReadAllText(_options.Options.Model.FullName);
try
{
// Deserialize model using Newtonsoft for now (has type information). This may change in .NET 5.
// https://github.com/dotnet/runtime/issues/30969
var model = JsonConvert.DeserializeObject(json, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All });
// Is it of the right type?
if (!(model is IApplicationModel appModel))
{
throw new InvalidCastException(string.Format(CultureInfo.CurrentCulture, ErrorMessages.ModelFileDoesNotContainAnApplicationModel, _options.Options.Model.FullName));
}
else
{
return appModel;
}
}
catch (Exception e) when (e is JsonSerializationException || e is SerializationException)
{
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogError(e, ErrorMessages.FailedDeserializingModel, _options.Options.Model.FullName, e.Message);
}
else
{
_logger.LogError(ErrorMessages.FailedDeserializingModel, _options.Options.Model.FullName, e.Message);
}
}
return null;
}
else
{
return null;
}
}
19
Source : RuntimeLogger.cs
with MIT License
from Azure
with MIT License
from Azure
void ILogger.Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
var isEnabled = (this as ILogger).IsEnabled(logLevel);
if (!isEnabled)
{
return;
}
var entry = new RuntimeLogEntry
{
Category = this.Category,
Level = logLevel,
Message = state.ToString(),
Exception = exception,
EventId = eventId.Id,
State = state,
};
if (state is string)
{
entry.StateText = state.ToString();
}
else if (state is IEnumerable<KeyValuePair<string, object>> properties)
{
entry.StateProperties = new Dictionary<string, object>();
foreach(var item in properties)
{
entry.StateProperties[item.Key] = item.Value;
}
}
if (this.Provider.ScopeProvider != null)
{
this.Provider.ScopeProvider.ForEachScope((obj, loggingProps) =>
{
if (entry.Scopes == null)
{
entry.Scopes = new List<RuntimeLogScope>();
}
var scope = new RuntimeLogScope();
entry.Scopes.Add(scope);
if (obj is string)
{
scope.Text = obj.ToString();
}
else if (obj is IEnumerable<KeyValuePair<string, object>> properties)
{
if (scope.Properties == null)
{
scope.Properties = new Dictionary<string, object>();
}
foreach (var item in properties)
{
scope.Properties[item.Key] = item.Value;
}
}
}, state);
}
this.Provider.WriteLog(entry, this.Resource, this.DetectorId);
}
19
Source : KafkaTopicScaler.cs
with MIT License
from Azure
with MIT License
from Azure
private ScaleStatus GetScaleStatusCore(int workerCount, KafkaTriggerMetrics[] metrics)
{
var status = new ScaleStatus
{
Vote = ScaleVote.None,
};
const int NumberOfSamplesToConsider = 5;
// At least 5 samples are required to make a scale decision for the rest of the checks.
if (metrics == null || metrics.Length < NumberOfSamplesToConsider)
{
return status;
}
var lastMetrics = metrics.Last();
long totalLag = lastMetrics.TotalLag;
long parreplacedionCount = lastMetrics.ParreplacedionCount;
long lagThreshold = this.lagThreshold;
// We shouldn't replacedign more workers than there are parreplacedions
// This check is first, because it is independent of load or number of samples.
if (parreplacedionCount > 0 && parreplacedionCount < workerCount)
{
status.Vote = ScaleVote.ScaleIn;
if (this.logger.IsEnabled(LogLevel.Information))
{
this.logger.LogInformation("WorkerCount ({workerCount}) > ParreplacedionCount ({parreplacedionCount}). For topic {topicName}, for consumer group {consumerGroup}.", workerCount, parreplacedionCount, this.topicName, this.consumerGroup);
this.logger.LogInformation("Number of instances ({workerCount}) is too high relative to number of parreplacedions ({parreplacedionCount}). For topic {topicName}, for consumer group {consumerGroup}.", workerCount, parreplacedionCount, this.topicName, this.consumerGroup);
}
return status;
}
// Check to see if the Kafka consumer has been empty for a while. Only if all metrics samples are empty do we scale down.
bool parreplacedionIsIdle = metrics.All(p => p.TotalLag == 0);
if (parreplacedionIsIdle)
{
status.Vote = ScaleVote.ScaleIn;
if (this.logger.IsEnabled(LogLevel.Information))
{
this.logger.LogInformation("Topic '{topicName}', for consumer group {consumerGroup}' is idle.", this.topicName, this.consumerGroup);
}
return status;
}
// Maintain a minimum ratio of 1 worker per lagThreshold --1,000 unprocessed message.
if (totalLag > workerCount * lagThreshold)
{
if (workerCount < parreplacedionCount)
{
status.Vote = ScaleVote.ScaleOut;
if (this.logger.IsEnabled(LogLevel.Information))
{
this.logger.LogInformation("Total lag ({totalLag}) is less than the number of instances ({workerCount}). Scale out, for topic {topicName}, for consumer group {consumerGroup}.", totalLag, workerCount, topicName, consumerGroup);
}
}
return status;
}
// Samples are in chronological order. Check for a continuous increase in unprocessed message count.
// If detected, this results in an automatic scale out for the site container.
if (metrics[0].TotalLag > 0)
{
if (workerCount < parreplacedionCount)
{
bool queueLengthIncreasing = IsTrueForLast(
metrics,
NumberOfSamplesToConsider,
(prev, next) => prev.TotalLag < next.TotalLag) && metrics[0].TotalLag > 0;
if (queueLengthIncreasing)
{
status.Vote = ScaleVote.ScaleOut;
if (this.logger.IsEnabled(LogLevel.Information))
{
this.logger.LogInformation("Total lag ({totalLag}) is less than the number of instances ({workerCount}). Scale out, for topic {topicName}, for consumer group {consumerGroup}.", totalLag, workerCount, topicName, consumerGroup);
}
return status;
}
}
}
if (workerCount > 1)
{
bool queueLengthDecreasing = IsTrueForLast(
metrics,
NumberOfSamplesToConsider,
(prev, next) => prev.TotalLag > next.TotalLag);
if (queueLengthDecreasing)
{
// Only vote down if the new workerCount / totalLag < threshold
// Example: 4 workers, only scale in if totalLag <= 2999 (3000 < (3 * 1000))
var proposedWorkerCount = workerCount - 1;
var proposedLagPerWorker = totalLag / proposedWorkerCount;
if (proposedLagPerWorker < lagThreshold)
{
status.Vote = ScaleVote.ScaleIn;
if (this.logger.IsEnabled(LogLevel.Information))
{
this.logger.LogInformation("Total lag length is decreasing for topic {topicName}, for consumer group {consumerGroup}.", this.topicName, this.consumerGroup);
}
}
}
}
return status;
}
19
Source : MultipleItemFunctionExecutor.cs
with MIT License
from Azure
with MIT License
from Azure
protected override async Task ReaderAsync(ChannelReader<IKafkaEventData[]> reader, CancellationToken cancellationToken, ILogger logger)
{
while (!cancellationToken.IsCancellationRequested && await reader.WaitToReadAsync(cancellationToken))
{
while (!cancellationToken.IsCancellationRequested && reader.TryRead(out var itemsToExecute))
{
try
{
// Try to publish them
var triggerInput = KafkaTriggerInput.New(itemsToExecute);
var triggerData = new TriggeredFunctionData
{
TriggerValue = triggerInput,
};
var functionResult = await this.ExecuteFunctionAsync(triggerData, cancellationToken);
var offsetsToCommit = new Dictionary<int, TopicParreplacedionOffset>();
for (var i=itemsToExecute.Length - 1; i >= 0; i--)
{
var currenreplacedem = itemsToExecute[i];
if (!offsetsToCommit.ContainsKey(currenreplacedem.Parreplacedion))
{
offsetsToCommit.Add(
currenreplacedem.Parreplacedion,
new TopicParreplacedionOffset(
currenreplacedem.Topic,
currenreplacedem.Parreplacedion,
currenreplacedem.Offset + 1)); // offset is inclusive when resuming
}
}
if (!cancellationToken.IsCancellationRequested)
{
this.Commit(offsetsToCommit.Values);
if (functionResult.Succeeded)
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Function executed with {batchSize} items in {topic} / {parreplacedions} / {offsets}",
itemsToExecute.Length,
itemsToExecute[0].Topic,
string.Join(",", offsetsToCommit.Keys),
string.Join(",", offsetsToCommit.Values.Select(x => x.Offset)));
}
}
else
{
logger.LogError(functionResult.Exception, "Failed to executed function with {batchSize} items in {topic} / {parreplacedions} / {offsets}",
itemsToExecute.Length,
itemsToExecute[0].Topic,
string.Join(",", offsetsToCommit.Keys),
string.Join(",", offsetsToCommit.Values.Select(x => x.Offset)));
}
}
}
catch (Exception ex)
{
logger.LogError(ex, $"Error in executor reader");
}
}
}
logger.LogInformation("Exiting reader {processName}", nameof(MultipleItemFunctionExecutor<TKey, TValue>));
}
19
Source : ReplaySafeLogger.cs
with MIT License
from Azure
with MIT License
from Azure
public bool IsEnabled(LogLevel logLevel)
{
return this.logger.IsEnabled(logLevel);
}
19
Source : AzureFunctionsFileHelper.cs
with MIT License
from Azure
with MIT License
from Azure
internal static void InitializeLibrdKafka(ILogger logger)
{
lock (librdkafkaInitializationLock)
{
if (librdkafkaInitialized)
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Librdkafka initialization: skipping as the initialization already happened");
}
return;
}
librdkafkaInitialized = true;
var userSpecifiedLibrdKafkaLocation = Environment.GetEnvironmentVariable(LibrdKafkaLocationEnvVarName);
if (!string.IsNullOrWhiteSpace(userSpecifiedLibrdKafkaLocation))
{
logger.LogDebug("Librdkafka initialization: loading librdkafka from user specified location: {librdkafkaPath}", userSpecifiedLibrdKafkaLocation);
Confluent.Kafka.Library.Load(userSpecifiedLibrdKafkaLocation);
return;
}
if (!IsRunningAsFunctionInAzureOrContainer())
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Librdkafka initialization: skipping as we are not running in Azure or a container");
}
return;
}
var possibleLibrdKafkaLibraryPaths = new List<string>();
var os = Environment.GetEnvironmentVariable(OSEnvVarName, EnvironmentVariableTarget.Process) ?? string.Empty;
var isWindows = os.IndexOf("windows", 0, StringComparison.InvariantCultureIgnoreCase) != -1;
if (isWindows)
{
var websiteBitness = Environment.GetEnvironmentVariable(SiteBitnessEnvVarName) ?? string.Empty;
var is32 = websiteBitness.Equals(ProcessArchitecturex86Value, StringComparison.InvariantCultureIgnoreCase);
var architectureFolderName = is32 ? Windows32ArchFolderName : Windows64ArchFolderName;
var functionBaseFolder = GetFunctionBaseFolder();
// Functions v2 have the runtime under 'D:\home\site\wwwroot\runtimes'
possibleLibrdKafkaLibraryPaths.Add(Path.Combine(functionBaseFolder, RuntimesFolderName, architectureFolderName, NativeFolderName, LibrdKafkaWindowsFileName));
// Functions v3 have the runtime under 'D:\home\site\wwwroot\bin\runtimes'
possibleLibrdKafkaLibraryPaths.Add(Path.Combine(functionBaseFolder, BinFolderName, RuntimesFolderName, architectureFolderName, NativeFolderName, LibrdKafkaWindowsFileName));
}
else
{
logger.LogInformation("Librdkafka initialization: running in non-Windows OS, expecting librdkafka to be there");
}
if (possibleLibrdKafkaLibraryPaths.Count > 0)
{
foreach (var librdKafkaLibraryPath in possibleLibrdKafkaLibraryPaths)
{
if (File.Exists(librdKafkaLibraryPath))
{
logger.LogDebug("Librdkafka initialization: loading librdkafka from {librdkafkaPath}", librdKafkaLibraryPath);
Confluent.Kafka.Library.Load(librdKafkaLibraryPath);
return;
}
}
logger.LogWarning("Librdkafka initialization: did not attempt to load librdkafka because the desired file(s) does not exist: '{searchedPaths}' You can ignore this warning when you use extension bundle.", string.Join(",", possibleLibrdKafkaLibraryPaths));
}
else
{
logger.LogInformation("Librdkafka initialization: could not find dll location");
}
}
}
19
Source : LoggerExtension.cs
with MIT License
from Azure
with MIT License
from Azure
public bool IsEnabled(LogLevel logLevel) => _logger.IsEnabled(logLevel);
19
Source : ConnectionFactory.cs
with MIT License
from Azure
with MIT License
from Azure
public bool IsEnabled(LogLevel logLevel)
{
return _inner.IsEnabled(logLevel);
}
19
Source : MasterCheckpointer.cs
with MIT License
from Azure
with MIT License
from Azure
public static void CommitFinished(MasterCheckpointer masterCheckpointer)
{
if (Log.IsEnabled(LogLevel.Debug))
{
Log.LogDebug((int)EventIds.CommitFinished, "[MasterCheckpointerCommitFinished] {0}", GetContextString(masterCheckpointer));
}
}
19
Source : MasterCheckpointer.cs
with MIT License
from Azure
with MIT License
from Azure
public static void CreateStart(string id)
{
if (Log.IsEnabled(LogLevel.Debug))
{
Log.LogDebug((int)EventIds.CreateStart, "[MasterCheckpointerCreateStart] MasterCheckpointerId: {0}", id);
}
}
19
Source : MasterCheckpointer.cs
with MIT License
from Azure
with MIT License
from Azure
public static void CreateFinished(MasterCheckpointer masterCheckpointer)
{
if (Log.IsEnabled(LogLevel.Debug))
{
Log.LogDebug((int)EventIds.CreateFinished, "[MasterCheckpointerCreateFinished] {0}", GetContextString(masterCheckpointer));
}
}
19
Source : MasterCheckpointer.cs
with MIT License
from Azure
with MIT License
from Azure
public static void CreateChildFinished(MasterCheckpointer masterCheckpointer, string id)
{
if (Log.IsEnabled(LogLevel.Debug))
{
Log.LogDebug((int)EventIds.CreateChildFinished, "[ChildCheckpointerCreateFinished] ChildCheckpointerId: {0}, {1}", id, GetContextString(masterCheckpointer));
}
}
19
Source : MasterCheckpointer.cs
with MIT License
from Azure
with MIT License
from Azure
public static void CommitStarted(MasterCheckpointer masterCheckpointer, int successfulCount, int remainingCount)
{
if (Log.IsEnabled(LogLevel.Debug))
{
Log.LogDebug((int)EventIds.CommitStarted, "[MasterCheckpointerCommitStarted] SuccessfulCount: {0}, RemainingCount: {1}, {2}", successfulCount, remainingCount, GetContextString(masterCheckpointer));
}
}
19
Source : MasterCheckpointer.cs
with MIT License
from Azure
with MIT License
from Azure
public static void CreateChildStart(MasterCheckpointer masterCheckpointer, string id)
{
if (Log.IsEnabled(LogLevel.Debug))
{
Log.LogDebug((int)EventIds.CreateChildStart, "[ChildCheckpointerCreateStart] ChildCheckpointerId: {0}, {1}", id, GetContextString(masterCheckpointer));
}
}
19
Source : MasterCheckpointer.cs
with MIT License
from Azure
with MIT License
from Azure
public static void Admit(MasterCheckpointer masterCheckpointer, long messageOffset, bool isClosed)
{
if (Log.IsEnabled(LogLevel.Debug))
{
Log.LogDebug((int)EventIds.Admit, "[MasterCheckpointerAdmit] jMessageOffset: {0}, IsClosed: {1}, {2}", messageOffset, isClosed, GetContextString(masterCheckpointer));
}
}
19
Source : MainController.cs
with MIT License
from Azure-Samples
with MIT License
from Azure-Samples
[HttpGet("enqueue/{source}")]
public async Task<IActionResult> EnqueueAsync(
[FromServices]IRabbitMQProducer rabbitMQProducer, // Using FromServices to allow lazy creation of RabbitMQ connection
string source,
string eventName = null)
{
await Task.Delay(100);
FailGenerator.FailIfNeeded(1);
var apiFullUrl = $"{timeApiUrl}/api/time/localday";
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Getting time from {url}", apiFullUrl);
}
var day = await httpClientFactory.CreateClient().GetStringAsync(apiFullUrl);
var jsonResponse = new EnqueuedMessage { Day = day, EventName = eventName, Source = source ?? "N/a" };
var message = System.Text.Json.JsonSerializer.Serialize(jsonResponse);
rabbitMQProducer.Publish(message);
metrics.TrackItemEnqueued(1, source);
return new JsonResult(jsonResponse);
}
19
Source : WebQueueConsumerHostedService.cs
with MIT License
from Azure-Samples
with MIT License
from Azure-Samples
private async Task ProcessWebQueueMessageAsync(object sender, BasicDeliverEventArgs @event)
{
// ExtractActivity creates the Activity setting the parent based on the RabbitMQ "traceparent" header
var activity = @event.ExtractActivity("Process single RabbitMQ message");
ISpan span = null;
IOperationHolder<DependencyTelemetry> operation = null;
var processingSucceeded = false;
string source = string.Empty;
IDisposable loggingScope = null;
try
{
if (tracer != null)
{
// OpenTelemetry seems to require the Activity to have started, unlike AI SDK
activity.Start();
tracer.StartActiveSpanFromActivity(activity.OperationName, activity, SpanKind.Consumer, out span);
span.SetAttribute("queue", Constants.WebQueueName);
}
using (operation = telemetryClient?.StartOperation<DependencyTelemetry>(activity))
{
if (operation != null)
{
operation.Telemetry.Properties.Add("queue", Constants.WebQueueName);
operation.Telemetry.Type = ApplicationInformation.Name;
operation.Telemetry.Target = this.rabbitMQHostName;
}
loggingScope = logger.BeginScope("Starting message processing");
// Get the payload
var message = JsonSerializer.Deserialize<EnqueuedMessage>(@event.Body, jsonSerializerOptions);
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Processing message from {source}: {message}", message.Source, Encoding.UTF8.GetString(@event.Body));
}
source = message.Source;
if ("error".Equals(message.EventName, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidEventNameException("Invalid event name");
}
var apiFullUrl = $"{timeApiURL}/api/time/dbtime";
var time = await httpClientFactory.CreateClient().GetStringAsync(apiFullUrl);
if (!string.IsNullOrEmpty(message.EventName))
{
span?.AddEvent(message.EventName);
telemetryClient?.TrackEvent(message.EventName);
}
}
processingSucceeded = true;
}
catch (Exception ex)
{
if (span != null)
{
span.SetAttribute("error", true);
span.Status = Status.Internal.WithDescription(ex.ToString());
}
if (operation != null)
{
operation.Telemetry.Success = false;
operation.Telemetry.ResultCode = "500";
// Track exception, adding the connection to the current activity
var exOperation = new ExceptionTelemetry(ex);
exOperation.Context.Operation.Id = operation.Telemetry.Context.Operation.Id;
exOperation.Context.Operation.ParentId = operation.Telemetry.Context.Operation.ParentId;
telemetryClient.TrackException(exOperation);
}
logger.LogError(ex, "Failed to process message from {source}", source);
}
finally
{
span?.End();
metrics.TrackItemProcessed(1, source, processingSucceeded);
loggingScope?.Dispose();
}
}
19
Source : TimeController.cs
with MIT License
from Azure-Samples
with MIT License
from Azure-Samples
[HttpGet("dbtime")]
public async Task<DateTime> GetDbTimeAsync()
{
FailGenerator.FailIfNeeded(1);
if (logger.IsEnabled(LogLevel.Debug))
{
LogRequestHeaders();
}
var result = await repository.GetTimeFromSqlAsync();
logger.LogInformation("{operation} result is {result}", nameof(repository.GetTimeFromSqlAsync), result);
return result;
}
19
Source : TimeController.cs
with MIT License
from Azure-Samples
with MIT License
from Azure-Samples
[HttpGet("localday")]
public string GetLocalDay()
{
FailGenerator.FailIfNeeded(1);
if (logger.IsEnabled(LogLevel.Debug))
{
LogRequestHeaders();
}
var result = DateTime.Now.DayOfWeek.ToString();
logger.LogInformation("Retrieved current day is {currentDay} at {time}", result, DateTime.UtcNow);
return result;
}
19
Source : SqlDeviceRepository.cs
with MIT License
from Azure-Samples
with MIT License
from Azure-Samples
public async Task<DateTime> GetTimeFromSqlAsync()
{
using var conn = new SqlConnection(this.connectionString);
await conn.OpenAsync();
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Getting date from Sql Server");
}
using var cmd = new SqlCommand("SELECT GETDATE()", conn);
var res = await cmd.ExecuteScalarAsync();
return (DateTime)res;
}
19
Source : LoggerExtensions.cs
with MIT License
from dotnet
with MIT License
from dotnet
public static void TraceBinary(this ILogger logger, ReadOnlyMemory<byte> data)
{
if (logger.IsEnabled(LogLevel.Trace))
{
LogBinaryTraceData(logger, Environment.NewLine + data.ToArray().HexDump(), null);
}
}
19
Source : DefaultGeneratedDocumentPublisher.cs
with MIT License
from dotnet
with MIT License
from dotnet
public override void PublishCSharp(string filePath, SourceText sourceText, int hostDoreplacedentVersion)
{
if (filePath is null)
{
throw new ArgumentNullException(nameof(filePath));
}
if (sourceText is null)
{
throw new ArgumentNullException(nameof(sourceText));
}
_projectSnapshotManagerDispatcher.replacedertDispatcherThread();
if (!_publishedCSharpData.TryGetValue(filePath, out var previouslyPublishedData))
{
previouslyPublishedData = PublishData.Default;
}
var textChanges = SourceTextDiffer.GetMinimalTextChanges(previouslyPublishedData.SourceText, sourceText);
if (textChanges.Count == 0 && hostDoreplacedentVersion == previouslyPublishedData.HostDoreplacedentVersion)
{
// Source texts match along with host doreplacedent versions. We've already published something that looks like this. No-op.
return;
}
if (_logger.IsEnabled(LogLevel.Trace))
{
var previousDoreplacedentLength = previouslyPublishedData.SourceText.Length;
var currentDoreplacedentLength = sourceText.Length;
var doreplacedentLengthDelta = sourceText.Length - previousDoreplacedentLength;
_logger.LogTrace(
"Updating C# buffer of {0} to correspond with host doreplacedent version {1}. {2} -> {3} = Change delta of {4} via {5} text changes.",
filePath,
hostDoreplacedentVersion,
previousDoreplacedentLength,
currentDoreplacedentLength,
doreplacedentLengthDelta,
textChanges.Count);
}
_publishedCSharpData[filePath] = new PublishData(sourceText, hostDoreplacedentVersion);
var request = new UpdateBufferRequest()
{
HostDoreplacedentFilePath = filePath,
Changes = textChanges,
HostDoreplacedentVersion = hostDoreplacedentVersion,
};
var result = _server.SendRequest(LanguageServerConstants.RazorUpdateCSharpBufferEndpoint, request);
// This is the call that actually makes the request, any SendRequest without a .Returning* after it will do nothing.
_ = result.ReturningVoid(CancellationToken.None);
}
19
Source : DefaultGeneratedDocumentPublisher.cs
with MIT License
from dotnet
with MIT License
from dotnet
public override void PublishHtml(string filePath, SourceText sourceText, int hostDoreplacedentVersion)
{
if (filePath is null)
{
throw new ArgumentNullException(nameof(filePath));
}
if (sourceText is null)
{
throw new ArgumentNullException(nameof(sourceText));
}
_projectSnapshotManagerDispatcher.replacedertDispatcherThread();
if (!_publishedHtmlData.TryGetValue(filePath, out var previouslyPublishedData))
{
previouslyPublishedData = PublishData.Default;
}
var textChanges = SourceTextDiffer.GetMinimalTextChanges(previouslyPublishedData.SourceText, sourceText);
if (textChanges.Count == 0 && hostDoreplacedentVersion == previouslyPublishedData.HostDoreplacedentVersion)
{
// Source texts match along with host doreplacedent versions. We've already published something that looks like this. No-op.
return;
}
if (_logger.IsEnabled(LogLevel.Trace))
{
var previousDoreplacedentLength = previouslyPublishedData.SourceText.Length;
var currentDoreplacedentLength = sourceText.Length;
var doreplacedentLengthDelta = sourceText.Length - previousDoreplacedentLength;
_logger.LogTrace(
"Updating HTML buffer of {0} to correspond with host doreplacedent version {1}. {2} -> {3} = Change delta of {4} via {5} text changes.",
filePath,
hostDoreplacedentVersion,
previousDoreplacedentLength,
currentDoreplacedentLength,
doreplacedentLengthDelta,
textChanges.Count);
}
_publishedHtmlData[filePath] = new PublishData(sourceText, hostDoreplacedentVersion);
var request = new UpdateBufferRequest()
{
HostDoreplacedentFilePath = filePath,
Changes = textChanges,
HostDoreplacedentVersion = hostDoreplacedentVersion,
};
var result = _server.SendRequest(LanguageServerConstants.RazorUpdateHtmlBufferEndpoint, request);
_ = result.ReturningVoid(CancellationToken.None);
}
19
Source : RazorDiagnosticsPublisher.cs
with MIT License
from dotnet
with MIT License
from dotnet
internal async Task PublishDiagnosticsAsync(DoreplacedentSnapshot doreplacedent)
{
var result = await doreplacedent.GetGeneratedOutputAsync();
var diagnostics = result.GetCSharpDoreplacedent().Diagnostics;
lock (PublishedDiagnostics)
{
if (PublishedDiagnostics.TryGetValue(doreplacedent.FilePath, out var previousDiagnostics) &&
diagnostics.SequenceEqual(previousDiagnostics))
{
// Diagnostics are the same as last publish
return;
}
PublishedDiagnostics[doreplacedent.FilePath] = diagnostics;
}
if (!doreplacedent.TryGetText(out var sourceText))
{
Debug.Fail("Doreplacedent source text should already be available.");
}
var convertedDiagnostics = diagnostics.Select(razorDiagnostic => RazorDiagnosticConverter.Convert(razorDiagnostic, sourceText));
PublishDiagnosticsForFilePath(doreplacedent.FilePath, convertedDiagnostics);
if (_logger.IsEnabled(LogLevel.Trace))
{
var diagnosticString = string.Join(", ", diagnostics.Select(diagnostic => diagnostic.Id));
_logger.LogTrace($"Publishing diagnostics for doreplacedent '{doreplacedent.FilePath}': {diagnosticString}");
}
}
19
Source : TestLoggerT.cs
with MIT License
from dotnet
with MIT License
from dotnet
public bool IsEnabled(LogLevel logLevel)
{
return _logger.IsEnabled(logLevel);
}
19
Source : AbstractConfigBuilder.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
protected void BuildSqlMap(ResourceType resourceType, string path)
{
switch (resourceType)
{
case ResourceType.Embedded:
case ResourceType.File:
{
var sqlMapXml = ResourceUtil.LoadAsXml(resourceType, path);
BuildSqlMap(sqlMapXml);
break;
}
case ResourceType.Directory:
case ResourceType.DirectoryWithAllSub:
{
SearchOption searchOption = SearchOption.TopDirectoryOnly;
if (resourceType == ResourceType.DirectoryWithAllSub)
{
searchOption = SearchOption.AllDirectories;
}
var dicPath = Path.Combine(AppContext.BaseDirectory, path);
var childSqlMapSources = Directory.EnumerateFiles(dicPath, "*.xml", searchOption);
foreach (var sqlMapPath in childSqlMapSources)
{
if (Logger.IsEnabled(LogLevel.Debug))
{
Logger.LogDebug($"BuildSqlMap.Child ->> Path :[{sqlMapPath}].");
}
var sqlMapXml = ResourceUtil.LoadFileAsXml(sqlMapPath);
BuildSqlMap(sqlMapXml);
}
break;
}
}
}
19
Source : DataSourceFilter.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
private AbstractDataSource GetDataSource(AbstractRequestContext context)
{
var sourceChoice = context.DataSourceChoice;
var database = context.ExecutionContext.SmartSqlConfig.Database;
AbstractDataSource choiceDataSource = database.Write;
var readDataSources = database.Reads;
if (sourceChoice != DataSourceChoice.Read || readDataSources == null || readDataSources.Count <= 0)
return choiceDataSource;
if (!string.IsNullOrEmpty(context.ReadDb))
{
if (!readDataSources.TryGetValue(context.ReadDb, out var readDataSource))
{
throw new SmartSqlException($"Can not find ReadDb:{context.ReadDb} .");
}
choiceDataSource = readDataSource;
}
else
{
var seekList = readDataSources.Values.Select(readDataSource => new WeightFilter<AbstractDataSource>.WeightSource
{
Source = readDataSource,
Weight = readDataSource.Weight
});
choiceDataSource = _weightFilter.Elect(seekList).Source;
}
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug($"DataSourceFilter GetDataSource Choice: {choiceDataSource.Name} .");
}
return choiceDataSource;
}
19
Source : DefaultDbSession.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public void Open()
{
var operationId = Guid.Empty;
try
{
operationId = _diagnosticListener.WriteDbSessionOpenBefore(this);
#region Impl
EnsureDbConnection();
if (Connection.State == ConnectionState.Closed)
{
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug($"OpenConnection to {DataSource.Name} .");
}
Connection.Open();
}
Opened?.Invoke(this, DbSessionEventArgs.None);
#endregion
_diagnosticListener.WriteDbSessionOpenAfter(operationId, this);
}
catch (Exception ex)
{
_diagnosticListener.WriteDbSessionOpenError(operationId, this, ex);
throw new SmartSqlException($"OpenConnection Unable to open connection to {DataSource.Name}.", ex);
}
}
19
Source : DefaultDbSession.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public async Task OpenAsync(CancellationToken cancellationToken)
{
var operationId = Guid.Empty;
try
{
operationId = _diagnosticListener.WriteDbSessionOpenBefore(this);
#region Impl
EnsureDbConnection();
if (Connection.State == ConnectionState.Closed)
{
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug($"OpenConnection to {DataSource.Name} .");
}
await Connection.OpenAsync(cancellationToken);
}
Opened?.Invoke(this, DbSessionEventArgs.None);
#endregion
_diagnosticListener.WriteDbSessionOpenAfter(operationId, this);
}
catch (Exception ex)
{
_diagnosticListener.WriteDbSessionOpenError(operationId, this, ex);
throw new SmartSqlException($"OpenConnection Unable to open connection to {DataSource.Name}.", ex);
}
}
19
Source : DefaultDbSession.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public DbTransaction BeginTransaction()
{
var operationId = Guid.Empty;
try
{
operationId = _diagnosticListener.WriteDbSessionBeginTransactionBefore(this);
#region Impl
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("BeginTransaction.");
}
Open();
Transaction = Connection.BeginTransaction();
TransactionBegan?.Invoke(this, DbSessionEventArgs.None);
#endregion
_diagnosticListener.WriteDbSessionBeginTransactionAfter(operationId, this);
return Transaction;
}
catch (Exception ex)
{
_diagnosticListener.WriteDbSessionBeginTransactionError(operationId, this, ex);
throw;
}
}
19
Source : DefaultDbSession.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public DbTransaction BeginTransaction(IsolationLevel isolationLevel)
{
var operationId = Guid.Empty;
try
{
operationId = _diagnosticListener.WriteDbSessionBeginTransactionBefore(this);
#region Impl
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("BeginTransaction.");
}
Open();
Transaction = Connection.BeginTransaction(isolationLevel);
TransactionBegan?.Invoke(this, DbSessionEventArgs.None);
#endregion
_diagnosticListener.WriteDbSessionBeginTransactionAfter(operationId, this);
return Transaction;
}
catch (Exception ex)
{
_diagnosticListener.WriteDbSessionBeginTransactionError(operationId, this, ex);
throw;
}
}
19
Source : DefaultDbSession.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public void CommitTransaction()
{
var operationId = Guid.Empty;
try
{
operationId = _diagnosticListener.WriteDbSessionCommitBefore(this);
#region Impl
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("CommitTransaction.");
}
if (Transaction == null)
{
if (_logger.IsEnabled(LogLevel.Error))
{
_logger.LogError("Before CommitTransaction,Please BeginTransaction first!");
}
throw new SmartSqlException("Before CommitTransaction,Please BeginTransaction first!");
}
Transaction.Commit();
Committed?.Invoke(this, DbSessionEventArgs.None);
#endregion
_diagnosticListener.WriteDbSessionCommitAfter(operationId, this);
}
catch (Exception ex)
{
_diagnosticListener.WriteDbSessionCommitError(operationId, this, ex);
throw;
}
finally
{
ReleaseTransaction();
}
}
19
Source : DefaultDbSession.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public void RollbackTransaction()
{
var operationId = Guid.Empty;
try
{
operationId = _diagnosticListener.WriteDbSessionRollbackBefore(this);
#region Impl
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("RollbackTransaction .");
}
if (Transaction == null)
{
if (_logger.IsEnabled(LogLevel.Warning))
{
_logger.LogWarning("Before RollbackTransaction,Please BeginTransaction first!");
}
_diagnosticListener.WriteDbSessionRollbackAfter(operationId, this);
return;
}
Transaction.Rollback();
Rollbacked?.Invoke(this, DbSessionEventArgs.None);
#endregion
_diagnosticListener.WriteDbSessionRollbackAfter(operationId, this);
}
catch (Exception ex)
{
_diagnosticListener.WriteDbSessionRollbackError(operationId, this, ex);
throw;
}
finally
{
ReleaseTransaction();
}
}
19
Source : DefaultDbSession.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public void Dispose()
{
var operationId = Guid.Empty;
try
{
operationId = _diagnosticListener.WriteDbSessionDisposeBefore(this);
#region Impl
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug($"Dispose. ");
}
if (Transaction != null)
{
RollbackTransaction();
}
if (Connection != null)
{
Connection.Close();
Connection.Dispose();
Connection = null;
}
Disposed?.Invoke(this, DbSessionEventArgs.None);
#endregion
_diagnosticListener.WriteDbSessionDisposeAfter(operationId, this);
}
catch (Exception ex)
{
_diagnosticListener.WriteDbSessionDisposeError(operationId, this, ex);
throw;
}
}
19
Source : DefaultDbSession.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public ExecutionContext Invoke<TResult>(AbstractRequestContext requestContext)
{
Stopwatch stopwatch = null;
var operationId = Guid.Empty;
var executionContext = new ExecutionContext
{
Request = requestContext,
SmartSqlConfig = SmartSqlConfig,
DbSession = this,
};
try
{
if (_logger.IsEnabled(LogLevel.Debug))
{
stopwatch = Stopwatch.StartNew();
}
operationId = _diagnosticListener.WriteDbSessionInvokeBefore(executionContext);
#region Impl
switch (executionContext.Type)
{
case ExecutionType.Execute:
case ExecutionType.ExecuteScalar:
case ExecutionType.QuerySingle:
case ExecutionType.GetDataSet:
case ExecutionType.GetDataTable:
{
executionContext.Result = new SingleResultContext<TResult>();
break;
}
case ExecutionType.Query:
{
executionContext.Result = new ListResultContext<TResult>();
break;
}
default:
throw new ArgumentOutOfRangeException();
}
requestContext.ExecutionContext = executionContext;
Pipeline.Invoke<TResult>(executionContext);
Invoked?.Invoke(this, new DbSessionInvokedEventArgs {ExecutionContext = executionContext});
#endregion
_diagnosticListener.WriteDbSessionInvokeAfter(operationId, executionContext);
return executionContext;
}
catch (Exception ex)
{
_diagnosticListener.WriteDbSessionInvokeError(operationId, executionContext, ex);
throw;
}
finally
{
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug(
$"Statement.Id:{requestContext.FullSqlId} Invoke Taken:{stopwatch?.ElapsedMilliseconds}.");
}
}
}
19
Source : DefaultDbSession.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public async Task<ExecutionContext> InvokeAsync<TResult>(AbstractRequestContext requestContext)
{
Stopwatch stopwatch = null;
Guid operationId = Guid.Empty;
var executionContext = new ExecutionContext
{
Request = requestContext,
SmartSqlConfig = SmartSqlConfig,
DbSession = this,
};
try
{
if (_logger.IsEnabled(LogLevel.Debug))
{
stopwatch = Stopwatch.StartNew();
}
operationId = _diagnosticListener.WriteDbSessionInvokeBefore(executionContext);
#region Impl
switch (executionContext.Type)
{
case ExecutionType.Execute:
case ExecutionType.ExecuteScalar:
case ExecutionType.QuerySingle:
case ExecutionType.GetDataSet:
case ExecutionType.GetDataTable:
{
executionContext.Result = new SingleResultContext<TResult>();
break;
}
case ExecutionType.Query:
{
executionContext.Result = new ListResultContext<TResult>();
break;
}
default:
throw new ArgumentOutOfRangeException();
}
requestContext.ExecutionContext = executionContext;
await Pipeline.InvokeAsync<TResult>(executionContext);
Invoked?.Invoke(this, new DbSessionInvokedEventArgs {ExecutionContext = executionContext});
#endregion
_diagnosticListener.WriteDbSessionInvokeAfter(operationId, executionContext);
return executionContext;
}
catch (Exception ex)
{
_diagnosticListener.WriteDbSessionInvokeError(operationId, executionContext, ex);
throw;
}
finally
{
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug(
$"Statement.Id:{requestContext.FullSqlId} Invoke Taken:{stopwatch?.ElapsedMilliseconds}.");
}
}
}
19
Source : AbstractCacheManager.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
protected void FlushOnExecuted(string fullSqlId)
{
if (StatementMappedFlushCache.TryGetValue(fullSqlId, out var caches))
{
if (Logger.IsEnabled(LogLevel.Debug))
{
Logger.LogDebug($"FlushOnExecuted -> FullSqlId:[{fullSqlId}] Start");
}
foreach (var cache in caches)
{
FlushCache(cache);
}
if (Logger.IsEnabled(LogLevel.Debug))
{
Logger.LogDebug($"FlushOnExecuted -> FullSqlId:[{fullSqlId}] End");
}
}
}
19
Source : AbstractCacheManager.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
private void FlushCache(Configuration.Cache cache)
{
if (Logger.IsEnabled(LogLevel.Debug))
{
Logger.LogDebug($"FlushCache Cache.Id:{cache.Id} .");
}
cache.Provider.Flush();
if (CacheMappedLastFlushTime.TryGetValue(cache, out _))
{
CacheMappedLastFlushTime[cache] = DateTime.Now;
}
}
19
Source : AbstractCacheManager.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
private void FlushOnInterval(object state)
{
if (Logger.IsEnabled(LogLevel.Debug))
{
Logger.LogDebug("FlushOnInterval Start");
}
foreach (var cacheKV in CacheMappedLastFlushTime)
{
var cache = cacheKV.Key;
var lastFlushTime = cacheKV.Value;
var nextFlushTime = lastFlushTime.Add(cache.FlushInterval.Interval);
if (DateTime.Now < nextFlushTime) continue;
if (!cache.Provider.SupportExpire)
{
FlushCache(cache);
}
}
if (Logger.IsEnabled(LogLevel.Debug))
{
Logger.LogDebug("FlushOnInterval End");
}
}
19
Source : AbstractCacheManager.cs
with Apache License 2.0
from dotnetcore
with Apache License 2.0
from dotnetcore
public virtual bool TryAddCache(ExecutionContext executionContext)
{
var cache = executionContext.Request.Cache;
if (cache == null)
{
return false;
}
var cacheKey = executionContext.Request.EnsureCacheKey();
var isSuccess = cache.Provider.TryAdd(cacheKey, executionContext.Result.GetData());
if (Logger.IsEnabled(LogLevel.Debug))
{
Logger.LogDebug(
$"HandleCache Cache.Id:{cache.Id} try add from Cache.Key:{cacheKey.Key} ->{isSuccess}!");
}
return isSuccess;
}
See More Examples