internal static IContextExceptionLogger Create(ErrorReportingServiceOptions options, IServiceProvider serviceProvider) { options = options ?? new ErrorReportingServiceOptions(); var errorReportingOptions = options.Options ?? ErrorReportingOptions.CreateInstance(); var eventTarget = options.EventTarget #pragma warning disable CS0618 // Type or member is obsolete ?? errorReportingOptions.EventTarget #pragma warning restore CS0618 // Type or member is obsolete ?? EventTarget.ForProject(Project.GetAndCheckProjectId(null, errorReportingOptions.MonitoredResource)); var client = options.Client #pragma warning disable CS0618 // Type or member is obsolete ?? eventTarget.LoggingClient #pragma warning restore CS0618 // Type or member is obsolete ?? LoggingServiceV2Client.Create(); var serviceContext = CreateServiceContext( Project.GetServiceName(options.ServiceName, errorReportingOptions.MonitoredResource), Project.GetServiceName(options.Version, errorReportingOptions.MonitoredResource)) ?? new Struct(); IConsumer <LogEntry> consumer = LogConsumer.Create(client, errorReportingOptions.BufferOptions, errorReportingOptions.RetryOptions); return(new ErrorReportingContextExceptionLogger(consumer, eventTarget, serviceContext, errorReportingOptions, serviceProvider)); }
/// <summary> /// Adds a <see cref="GoogleLoggerProvider"/> for <see cref="GoogleLogger"/>s. /// </summary> /// <param name="factory">The logger factory. Cannot be null.</param> /// <param name="projectId">Optional if running on Google App Engine or Google Compute Engine. /// The Google Cloud Platform project ID. If unspecified and running on GAE or GCE the project ID will be /// detected from the platform.</param> /// <param name="options">Optional, options for the logger.</param> /// <param name="client">Optional, logging client.</param> public static ILoggerFactory AddGoogle(this ILoggerFactory factory, string projectId = null, LoggerOptions options = null, LoggingServiceV2Client client = null) { options = options ?? LoggerOptions.Create(); projectId = Project.GetAndCheckProjectId(projectId, options.MonitoredResource); return(factory.AddGoogle(LogTarget.ForProject(projectId), options, client)); }
/// <summary> /// Adds a <see cref="GoogleLoggerProvider"/> for <see cref="GoogleLogger"/>s. /// </summary> /// <param name="factory">The logger factory. Cannot be null.</param> /// <param name="logTarget">Where to log to. Cannot be null.</param> /// <param name="options">Optional, options for the logger.</param> /// <param name="client">Optional, logging client.</param> public static ILoggerFactory AddGoogle(this ILoggerFactory factory, LogTarget logTarget, LoggerOptions options = null, LoggingServiceV2Client client = null) { GaxPreconditions.CheckNotNull(factory, nameof(factory)); factory.AddProvider(GoogleLoggerProvider.Create(logTarget, options, client)); return(factory); }
/// <summary> /// Adds a <see cref="GoogleLoggerProvider"/> for <see cref="GoogleLogger"/>s. /// </summary> /// <param name="factory">The logger factory. Cannot be null.</param> /// <param name="projectId">Optional if running on Google App Engine or Google Compute Engine. /// The Google Cloud Platform project ID. If unspecified and running on GAE or GCE the project ID will be /// detected from the platform.</param> /// <param name="options">Optional, options for the logger.</param> /// <param name="client">Optional, logging client.</param> public static ILoggerFactory AddGoogle(this ILoggerFactory factory, string projectId = null, LoggerOptions options = null, LoggingServiceV2Client client = null) { GaxPreconditions.CheckNotNull(factory, nameof(factory)); projectId = Project.GetAndCheckProjectId(projectId, options.MonitoredResource); return(factory.AddGoogle(LogTarget.ForProject(projectId), options, client)); }
internal LoggingClient(AgentOptions options, LoggingServiceV2Client loggingClient = null) { _logClient = loggingClient ?? LoggingServiceV2Client.Create(); _options = GaxPreconditions.CheckNotNull(options, nameof(options)); _logName = new LogName(_options.ProjectId, _options.LogName ?? $"{_options.Module}-{_options.Version}-debug-log"); }
public async Task Execute(string projectId, string logId, string message, IDictionary <string, string> entryLabels) { var client = LoggingServiceV2Client.Create(); LogName logName = new LogName(projectId, logId); LogEntry logEntry = new LogEntry { LogName = logName.ToString(), Severity = LogSeverity.Info, TextPayload = $"ChatBot - {message}" }; MonitoredResource resource = new MonitoredResource { Type = "global" }; if (entryLabels == null) { entryLabels = new Dictionary <string, string> { { "Timestamp", DateTime.Now.ToString() } }; } else { entryLabels.Add(new KeyValuePair <string, string>("Timestamp", DateTime.Now.ToString())); } await Task.Run(() => client.WriteLogEntries( LogNameOneof.From(logName), resource, entryLabels, new[] { logEntry }, _retryAWhile)); }
public async Task ListLogEntriesAsync() { // Snippet: ListLogEntriesAsync(IEnumerable<string>,string,string,string,int?,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) IEnumerable <string> projectIds = new List <string>(); string filter = ""; string orderBy = ""; // Make the request IPagedAsyncEnumerable <ListLogEntriesResponse, LogEntry> response = loggingServiceV2Client.ListLogEntriesAsync(projectIds, filter, orderBy); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((LogEntry item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over fixed-sized pages, lazily performing RPCs as required int pageSize = 10; IAsyncEnumerable <FixedSizePage <LogEntry> > fixedSizePages = response.AsPages().WithFixedSize(pageSize); await fixedSizePages.ForEachAsync((FixedSizePage <LogEntry> page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (LogEntry item in page) { Console.WriteLine(item); } }); // End snippet }
public GoogleCloudLoggingSink(GoogleCloudLoggingSinkOptions sinkOptions, MessageTemplateTextFormatter messageTemplateTextFormatter, int batchSizeLimit, TimeSpan period) : base(batchSizeLimit, period) { // logging client for google cloud apis // requires extra setup if credentials are passed as raw json text if (sinkOptions.GoogleCredentialJson == null) { _client = LoggingServiceV2Client.Create(); } else { var googleCredential = GoogleCredential.FromJson(sinkOptions.GoogleCredentialJson); var channel = new Grpc.Core.Channel(LoggingServiceV2Client.DefaultEndpoint.Host, googleCredential.ToChannelCredentials()); _client = LoggingServiceV2Client.Create(channel); } _sinkOptions = sinkOptions; _logFormatter = new LogFormatter(_sinkOptions, messageTemplateTextFormatter); _resource = new MonitoredResource { Type = sinkOptions.ResourceType }; foreach (var kvp in _sinkOptions.ResourceLabels) { _resource.Labels[kvp.Key] = kvp.Value; } var ln = new LogName(sinkOptions.ProjectId, sinkOptions.LogName); _logName = ln.ToString(); _logNameToWrite = LogNameOneof.From(ln); _serviceNameAvailable = !String.IsNullOrWhiteSpace(_sinkOptions.ServiceName); }
// For testing only. internal GoogleStackdriverAppender(LoggingServiceV2Client client, IScheduler scheduler, IClock clock) { _client = GaxPreconditions.CheckNotNull(client, nameof(client)); _scheduler = GaxPreconditions.CheckNotNull(scheduler, nameof(scheduler)); _clock = GaxPreconditions.CheckNotNull(clock, nameof(clock)); }
public static int Main(string[] args) { // Read projectId from args if (args.Length != 1) { Console.WriteLine("Usage: Project ID must be passed as first argument."); Console.WriteLine(); return(1); } string projectId = args[0]; // Create client LoggingServiceV2Client client = LoggingServiceV2Client.Create(); // Initialize request argument(s) LogNameOneof logName = LogNameOneof.From(new LogName(projectId, $"test-{Guid.NewGuid()}")); MonitoredResource resource = new MonitoredResource(); IDictionary <string, string> labels = new Dictionary <string, string>(); IEnumerable <LogEntry> entries = new List <LogEntry>(); // Call API method WriteLogEntriesResponse response = client.WriteLogEntries(logName, resource, labels, entries); // Show the result Console.WriteLine(response); // Success Console.WriteLine("Smoke test passed OK"); return(0); }
/// <summary> /// Create an <see cref="ILoggerProvider"/> for Google Cloud Logging. /// </summary> /// <param name="serviceProvider">The service provider to resolve additional services from. /// May be null, in which case additional services (such as custom labels) will not be used.</param> /// <param name="projectId">Optional if running on Google App Engine or Google Compute Engine. /// The Google Cloud Platform project ID. If unspecified and running on GAE or GCE the project ID will be /// detected from the platform.</param> /// <param name="options">Optional, options for the logger.</param> /// <param name="client">Optional, logging client.</param> public static GoogleLoggerProvider Create(IServiceProvider serviceProvider, string projectId = null, LoggerOptions options = null, LoggingServiceV2Client client = null) { options = options ?? LoggerOptions.Create(); projectId = Project.GetAndCheckProjectId(projectId, options.MonitoredResource); return(Create(LogTarget.ForProject(projectId), serviceProvider, options, client)); }
public GoogleCloudLoggingSink(GoogleCloudLoggingSinkOptions sinkOptions, MessageTemplateTextFormatter messageTemplateTextFormatter, int batchSizeLimit, TimeSpan period) : base(batchSizeLimit, period) { if (sinkOptions.GoogleCredentialJson == null) { _client = LoggingServiceV2Client.Create(); } else { var googleCredential = GoogleCredential.FromJson(sinkOptions.GoogleCredentialJson); var channel = new Grpc.Core.Channel(LoggingServiceV2Client.DefaultEndpoint.Host, googleCredential.ToChannelCredentials()); _client = LoggingServiceV2Client.Create(channel); } _sinkOptions = sinkOptions; _resource = new MonitoredResource { Type = sinkOptions.ResourceType }; foreach (var kvp in _sinkOptions.ResourceLabels) { _resource.Labels[kvp.Key] = kvp.Value; } var ln = new LogName(sinkOptions.ProjectId, sinkOptions.LogName); _logName = ln.ToString(); _logNameToWrite = LogNameOneof.From(ln); _messageTemplateTextFormatter = messageTemplateTextFormatter; }
/// <summary> /// Creates a new <see cref="EventTarget"/> instance that will report to the Stackdriver Logging API. /// The events are then automatically propigated to the Stackdriver Error Logging API from the /// Stackdriver Logging API. /// </summary> /// <remarks> /// For more information see "Formatting Log Error Messages" /// (https://cloud.google.com/error-reporting/docs/formatting-error-messages). /// </remarks> /// <param name="projectId">The Google Cloud Platform project Id. Cannot be null.</param> /// <param name="logName">The log name. Cannot be null.</param> /// <param name="loggingClient">The logging client.</param> /// <param name="monitoredResource">Optional, the monitored resource. The monitored resource will /// be automatically detected if it is not set and will default to the global resource if the detection fails. /// See: https://cloud.google.com/logging/docs/api/v2/resource-list </param> public static EventTarget ForLogging(string projectId, string logName = LogNameDefault, LoggingServiceV2Client loggingClient = null, MonitoredResource monitoredResource = null) { var logTarget = LogTarget.ForProject(GaxPreconditions.CheckNotNull(projectId, nameof(projectId))); return(ForLogging(logTarget, logName, loggingClient, monitoredResource)); }
/// <summary> /// Create an <see cref="ILoggerProvider"/> for Google Cloud Logging. /// </summary> public static GoogleLoggerProvider Create(IServiceProvider serviceProvider, LoggingServiceOptions options = null) { options = options ?? new LoggingServiceOptions(); var loggingOptions = options.Options ?? LoggingOptions.Create(); var logTarget = options.LogTarget ?? LogTarget.ForProject(Project.GetAndCheckProjectId(null, loggingOptions.MonitoredResource)); var serviceContext = ServiceContextUtils.CreateServiceContext( Project.GetServiceName(options.ServiceName, loggingOptions.MonitoredResource), Project.GetServiceName(options.Version, loggingOptions.MonitoredResource)); var client = options.Client ?? LoggingServiceV2Client.Create(); IConsumer <LogEntry> consumer = LogConsumer.Create(client, loggingOptions.BufferOptions, loggingOptions.RetryOptions); var provider = new GoogleLoggerProvider(consumer, logTarget, serviceContext, loggingOptions, serviceProvider); var writer = options.LoggerDiagnosticsOutput; if (writer != null) { // The log name is the ASP.NET Core log name, not the "/projects/xyz/logs/abc" log name in the resource. // We don't currently use this in the diagnostics, but if we ever start to do so, SampleLogName seems // like a reasonably clear example. ((GoogleLogger)provider.CreateLogger("SampleLogName")).WriteDiagnostics(writer); } return(provider); }
// [START write_log_entry] private void WriteLogEntry(string logId, string message) { var client = LoggingServiceV2Client.Create(); string logName = $"projects/{s_projectId}/logs/{logId}"; LogEntry logEntry = new LogEntry(); logEntry.LogName = logName; logEntry.Severity = LogSeverity.Info; Type myType = typeof(LoggingSample); string entrySeverity = logEntry.Severity.ToString().ToUpper(); logEntry.TextPayload = $"{entrySeverity} {myType.Namespace}.LoggingSample - {message}"; // Set the resource type to control which GCP resource the log entry belongs to. // See the list of resource types at: // https://cloud.google.com/logging/docs/api/v2/resource-list // This sample uses 'global' which will cause log entries to appear in the // "Global" resource list of the Developers Console Logs Viewer: // https://console.cloud.google.com/logs/viewer MonitoredResource resource = new MonitoredResource(); resource.Type = "global"; // Create dictionary object to add custom labels to the log entry. IDictionary <string, string> entryLabels = new Dictionary <string, string>(); entryLabels.Add("size", "large"); entryLabels.Add("color", "red"); // Add log entry to collection for writing. Multiple log entries can be added. IEnumerable <LogEntry> logEntries = new LogEntry[] { logEntry }; client.WriteLogEntries(logName, resource, entryLabels, logEntries); Console.WriteLine($"Created log entry in log-id: {logId}."); }
// [END update_log_sink] // [START delete_log] private void DeleteLog(string logId) { var client = LoggingServiceV2Client.Create(); string logName = $"projects/{s_projectId}/logs/{logId}"; client.DeleteLog(logName); Console.WriteLine($"Deleted {logId}."); }
/// <summary> /// Creates a new <see cref="EventTarget"/> instance that will report to the Stackdriver Logging API. /// The events are then automatically propigated to the Stackdriver Error Logging API from the /// Stackdriver Logging API. /// </summary> /// <remarks> /// For more information see "Formatting Log Error Messages" /// (https://cloud.google.com/error-reporting/docs/formatting-error-messages). /// </remarks> /// <param name="projectId">Optional if running on Google App Engine or Google Compute Engine. /// The Google Cloud Platform project ID. If running on GAE or GCE the project ID will be /// detected from the platform.</param> /// <param name="logName">The log name. Cannot be null.</param> /// <param name="loggingClient">The logging client.</param> /// <param name="monitoredResource">Optional, the monitored resource. The monitored resource will /// be automatically detected if it is not set and will default to the global resource if the detection fails. /// See: https://cloud.google.com/logging/docs/api/v2/resource-list </param> public static EventTarget ForLogging(string projectId = null, string logName = LogNameDefault, LoggingServiceV2Client loggingClient = null, MonitoredResource monitoredResource = null) { projectId = CommonUtils.GetAndCheckProjectId(projectId, monitoredResource); var logTarget = LogTarget.ForProject(projectId); return(ForLogging(logTarget, logName, loggingClient, monitoredResource)); }
public StackdriverLogger(string projectId, string logId) { _client = LoggingServiceV2Client.Create(); _logName = LogNameOneof.From(new LogName(projectId, logId)); _resource = new MonitoredResource { Type = "gce_backend_service" }; }
// [END logging_update_sink] // [START logging_delete_log] private void DeleteLog(string logId) { var client = LoggingServiceV2Client.Create(); LogName logName = new LogName(s_projectId, logId); client.DeleteLog(logName, _retryAWhile); Console.WriteLine($"Deleted {logId}."); }
/// <summary> /// Creates an <see cref="IConsumer{LogEntry}"/> based on the client and options. /// </summary> /// <param name="client">A client to send log entries with. Must not be null.</param> /// <param name="bufferOptions">The buffering options. Must not be null.</param> /// <param name="retryOptions">The retry options. Must not be null.</param> public static IConsumer <LogEntry> Create(LoggingServiceV2Client client, BufferOptions bufferOptions, RetryOptions retryOptions) { GaxPreconditions.CheckNotNull(client, nameof(client)); GaxPreconditions.CheckNotNull(bufferOptions, nameof(bufferOptions)); GaxPreconditions.CheckNotNull(retryOptions, nameof(retryOptions)); return(ConsumerFactory <LogEntry> .GetConsumer( new GrpcLogConsumer(client), MessageSizer <LogEntry> .GetSize, bufferOptions, retryOptions)); }
// For testing only. internal GoogleStackdriverTarget(LoggingServiceV2Client client, Platform platform) { OptimizeBufferReuse = true; ResourceLabels = new List <TargetPropertyWithContext>(); _contextProperties = new List <TargetPropertyWithContext>(); _client = client; _platform = platform; _writeLogEntriesBegin = WriteLogEntriesBegin; _writeLogEntriesCompleted = WriteLogEntriesCompleted; }
/// <summary> /// Create a new <see cref="Agent"/>. /// </summary> public Agent(AgentOptions options, Controller2Client controlClient = null, LoggingServiceV2Client loggingClient = null) { _agentOptions = GaxPreconditions.CheckNotNull(options, nameof(options)); _debuggerClient = new DebuggerClient(options, controlClient); _loggingClient = new LoggingClient(options, loggingClient); _cts = new CancellationTokenSource(); _tcs = new TaskCompletionSource <bool>(); _breakpointManager = new BreakpointManager(); _debuggerOptions = DebuggerOptions.FromAgentOptions(_agentOptions); }
/// <summary>Snippet for DeleteLog</summary> public void DeleteLog() { // Snippet: DeleteLog(LogNameOneof,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) LogNameOneof logName = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")); // Make the request loggingServiceV2Client.DeleteLog(logName); // End snippet }
/// <summary> /// Creates a new <see cref="EventTarget"/> instance that will report to the Stackdriver Logging API. /// The events are then automatically propigated to the Stackdriver Error Logging API from the /// Stackdriver Logging API. /// </summary> /// <remarks> /// For more information see "Formatting Log Error Messages" /// (https://cloud.google.com/error-reporting/docs/formatting-error-messages). /// </remarks> /// <param name="logTarget">Where to log to, such as a project or organization. Cannot be null.</param> /// <param name="logName">The log name. Cannot be null.</param> /// <param name="loggingClient">The logging client.</param> /// <param name="monitoredResource">Optional, the monitored resource. The monitored resource will /// be automatically detected if it is not set and will default to the global resource if the detection fails. /// See: https://cloud.google.com/logging/docs/api/v2/resource-list </param> public static EventTarget ForLogging(LogTarget logTarget, string logName = LogNameDefault, LoggingServiceV2Client loggingClient = null, MonitoredResource monitoredResource = null) { return(new EventTarget { Kind = EventTargetKind.Logging, LoggingClient = loggingClient ?? LoggingServiceV2Client.Create(), LogTarget = GaxPreconditions.CheckNotNull(logTarget, nameof(logTarget)), LogName = GaxPreconditions.CheckNotNullOrEmpty(logName, nameof(logName)), MonitoredResource = monitoredResource ?? MonitoredResourceBuilder.FromPlatform(), }); }
public void DeleteLog() { // Snippet: DeleteLog(string,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) string formattedLogName = LoggingServiceV2Client.FormatLogName("[PROJECT]", "[LOG]"); // Make the request loggingServiceV2Client.DeleteLog(formattedLogName); // End snippet }
// [END logging_write_log_entry] // [START logging_list_log_entries] private void ListLogEntries(string logId) { var client = LoggingServiceV2Client.Create(); LogName logName = new LogName(s_projectId, logId); ProjectName projectName = new ProjectName(s_projectId); var results = client.ListLogEntries(Enumerable.Repeat(projectName, 1), $"logName={logName.ToString()}", "timestamp desc", callSettings: _retryAWhile); foreach (var row in results) { Console.WriteLine($"{row.TextPayload.Trim()}"); } }
public async Task DeleteLogAsync() { // Snippet: DeleteLogAsync(string,CallSettings) // Additional: DeleteLogAsync(string,CancellationToken) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) string formattedLogName = LoggingServiceV2Client.FormatLogName("[PROJECT]", "[LOG]"); // Make the request await loggingServiceV2Client.DeleteLogAsync(formattedLogName); // End snippet }
/// <summary> /// Create an <see cref="ILoggerProvider"/> for Google Cloud Logging. /// </summary> /// <param name="logTarget">Where to log to. Must not be null.</param> /// <param name="serviceProvider">Optional, the service provider to resolve additional services from. May be null, /// in which case additional services (such as custom labels) will not be used.</param> /// <param name="options">Optional, options for the logger.</param> /// <param name="client">Optional, logging client.</param> public static GoogleLoggerProvider Create(LogTarget logTarget, IServiceProvider serviceProvider, LoggerOptions options = null, LoggingServiceV2Client client = null) { // Check params and set defaults if unset. GaxPreconditions.CheckNotNull(logTarget, nameof(logTarget)); client = client ?? LoggingServiceV2Client.Create(); options = options ?? LoggerOptions.Create(); // Get the proper consumer from the options and add a logger provider. IConsumer <LogEntry> consumer = LogConsumer.Create(client, options.BufferOptions, options.RetryOptions); return(new GoogleLoggerProvider(consumer, logTarget, options, serviceProvider)); }
public LoggingCloud() { var loggingCredentials = File.ReadAllText("credentials.json"); client = new LoggingServiceV2ClientBuilder { JsonCredentials = loggingCredentials }.Build(); logName = new LogName("lacaliforniabot", Configuration.BasicConfiguration.Channel.ToLowerInvariant()); monitoredResource = new MonitoredResource { Type = "global" }; }
public CloudLoggingServicecs(IConfiguration configuration) { _configuration = configuration; var helper = new CloudLoggingHelper(_configuration); googleCredential = helper.GetGoogleCredential(); channel = new Channel( LoggingServiceV2Client.DefaultEndpoint.Host, LoggingServiceV2Client.DefaultEndpoint.Port, googleCredential.ToChannelCredentials() ); client = LoggingServiceV2Client.Create(channel); projectId = helper.GetProjectId(); }