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); }
public void WriteLogEntry_MessageWithSubstitution() { string logMessageFormat = "This is a log $0"; StackdriverVariable[] evaluatedExpressions = new StackdriverVariable[] { new StackdriverVariable() { Value = "test1" } }; Debugger.V2.Breakpoint breakpoint = new Debugger.V2.Breakpoint() { LogLevel = Debugger.V2.Breakpoint.Types.LogLevel.Warning, LogMessageFormat = logMessageFormat, EvaluatedExpressions = { evaluatedExpressions }, }; LogEntry logEntry = new LogEntry { LogName = _logNameObj.ToString(), Severity = Logging.Type.LogSeverity.Warning, TextPayload = $"LOGPOINT: This is a log {evaluatedExpressions[0].Value}" }; _client.WriteLogEntry(breakpoint); _mockLoggingClient.Verify(client => client.WriteLogEntries(LogNameOneof.From(_logNameObj), _resource, null, new[] { logEntry }, null), Times.Once()); }
public void WriteLogEntry_ErrorBreakpoint() { string logMessageFormat = "This is a log $0"; Debugger.V2.Breakpoint breakpoint = new Debugger.V2.Breakpoint() { LogLevel = Debugger.V2.Breakpoint.Types.LogLevel.Warning, LogMessageFormat = logMessageFormat, Status = new Debugger.V2.StatusMessage() { Description = new Debugger.V2.FormatMessage { Format = "This is an error" }, IsError = true } }; LogEntry logEntry = new LogEntry { LogName = _logNameObj.ToString(), Severity = Logging.Type.LogSeverity.Warning, TextPayload = "LOGPOINT: Error evaluating logpoint \"This is a log $0\": This is an error." }; _client.WriteLogEntry(breakpoint); _mockLoggingClient.Verify(client => client.WriteLogEntries(LogNameOneof.From(_logNameObj), _resource, null, new[] { logEntry }, null), Times.Once()); }
public static string WriteLog( string msg, Guid guid, [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0, [CallerMemberName] string memberName = "") { var assembly = Assembly.GetCallingAssembly(); var assemblyName = assembly.GetName(); LogName logName = new LogName(_projectId, _logid); LogEntry logEntry = new LogEntry { LogName = logName.ToString(), Severity = LogSeverity.Error, TextPayload = msg }; IDictionary <string, string> entryLabels = new Dictionary <string, string> { { "source_file", sourceFilePath }, { "source_line", sourceLineNumber.ToString() }, { "member_name", memberName }, { "assembly_name", assemblyName.Name }, { "assembly_version", assemblyName.Version.ToString() }, { "guid", guid.ToString() } }; _client.Value.WriteLogEntries(LogNameOneof.From(logName), _resource.Value, entryLabels, new[] { logEntry }, null); return(logEntry.ToString()); }
public void WriteLogEntry_MessageWithComplexSubstitution() { string logMessageFormat = "I lost $$$0 today in the $1."; StackdriverVariable[] evaluatedExpressions = new StackdriverVariable[] { new StackdriverVariable() { Value = "10000" }, new StackdriverVariable() { Value = "stock market" } }; Debugger.V2.Breakpoint breakpoint = new Debugger.V2.Breakpoint() { LogLevel = Debugger.V2.Breakpoint.Types.LogLevel.Warning, LogMessageFormat = logMessageFormat, EvaluatedExpressions = { evaluatedExpressions }, }; LogEntry logEntry = new LogEntry { LogName = _logNameObj.ToString(), Severity = Logging.Type.LogSeverity.Warning, TextPayload = $"LOGPOINT: I lost ${evaluatedExpressions[0].Value} today in the {evaluatedExpressions[1].Value}." }; _client.WriteLogEntry(breakpoint); _mockLoggingClient.Verify(client => client.WriteLogEntries(LogNameOneof.From(_logNameObj), _resource, null, new[] { logEntry }, null), Times.Once()); }
public static void WriteExceptionalLog(Exception exceptionalSunny) { LogName logName = new LogName(ProjectId, LogId); var jsonPayload = CreateJsonPayload(); var value = new ProtoWellKnownTypes.Value() { StringValue = exceptionalSunny.ToString() }; jsonPayload.Fields[MessageFieldName] = value; LogEntry logEntry = new LogEntry { LogName = logName.ToString(), Severity = LogSeverity.Error, JsonPayload = jsonPayload }; MonitoredResource resource = new MonitoredResource { Type = "global" }; // global does not use label. // resource.Labels["name"] = "This_is_another_name"; IDictionary <string, string> entryLabels = new Dictionary <string, string> { { "size", "large" }, { "color", "red" } }; _client.Value.WriteLogEntries(LogNameOneof.From(logName), resource, entryLabels, new[] { logEntry }, null); //TestTrace($"Written entry {logEntry.ToString()}"); }
public static void WriteLog() { LogName logName = new LogName("mars-148601", "log_id_tide_2"); LogEntry logEntry = new LogEntry { LogName = logName.ToString(), Severity = LogSeverity.Error, JsonPayload = ReadJson() }; MonitoredResource resource = new MonitoredResource { Type = "logging_log" }; resource.Labels["name"] = "This_is_another_name"; IDictionary <string, string> entryLabels = new Dictionary <string, string> { { "size", "large" }, { "color", "red" } }; _client.Value.WriteLogEntries(LogNameOneof.From(logName), resource, entryLabels, new[] { logEntry }, null); Console.WriteLine($"Created log entry {logEntry}."); }
protected virtual async Task CreateLog <T>(string id, LogSeverity severity, string message, IDictionary <string, string> labels = null, CancellationToken cancellationToken = default) where T : class { // Prepare new log entry. LogEntry entry = new LogEntry(); var logId = id; LogName logName = new LogName(GCPConfiguration.ProjectId, logId); LogNameOneof logNameToWrite = LogNameOneof.From(logName); entry.LogName = logName.ToString(); entry.Severity = severity; // Create log entry message. string messageId = DateTime.Now.Millisecond.ToString(); Type type = typeof(T); string entrySeverity = entry.Severity.ToString().ToUpper(); entry.TextPayload = $"{messageId} {entrySeverity} {type.Namespace} - {message}"; // Set the resource type to control which GCP resource the log entry belongs to. MonitoredResource resource = new MonitoredResource { Type = "global" }; // Add log entry to collection for writing. Multiple log entries can be added. IEnumerable <LogEntry> logEntries = new LogEntry[] { entry }; // Write new log entry. await LogClient.WriteLogEntriesAsync(logNameToWrite, resource, labels, logEntries); }
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 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; }
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> /// Substitutes the log message format in breakpoint and writes /// the result as a log entry to the log _logName. /// </summary> /// <returns>WriteLogEntriesResponse from the API.</returns> public WriteLogEntriesResponse WriteLogEntry(StackdriverBreakpoint breakpoint) { LogEntry logEntry = new LogEntry { LogName = _logName.ToString(), Severity = _logSeverityConversion[breakpoint.LogLevel], }; if (breakpoint.Status?.IsError ?? false) { // The .NET Debugger does not use parameters field so we can just use format directly. logEntry.TextPayload = $"{LogpointMessageStart}Error evaluating logpoint \"{breakpoint.LogMessageFormat}\": {breakpoint.Status?.Description?.Format}."; } else { logEntry.TextPayload = SubstituteLogMessageFormat( breakpoint.LogMessageFormat, breakpoint.EvaluatedExpressions.ToList()); } // TODO(quoct): Detect whether we are on gke and use gke_container. MonitoredResource resource = new MonitoredResource { Type = "global" }; return(_logClient.WriteLogEntries(LogNameOneof.From(_logName), resource, null, new[] { logEntry })); }
static public void WriteEntry(string message, bool appendGit = true) { LogName logName = new LogName(ProjectId, LogId); LogEntry log = new LogEntry { LogName = logName.ToString(), Severity = LogSeverity.Info, TextPayload = message }; IDictionary <string, string> entryLabels = new Dictionary <string, string> { { "size", "large" }, { "color", "red" } }; if (appendGit && SourceRevision.GitRevisionId != null) { entryLabels.Add(SourceRevision.GitRevisionIdLogLabel, SourceRevision.GitRevisionId); } MonitoredResource resource = new MonitoredResource { Type = "global" }; _client.Value.WriteLogEntries( LogNameOneof.From(logName), resource, entryLabels, new[] { log }, null); }
public void CreateNewLogging(string message, string logId, string type, IDictionary <string, string> entryLabels, LogSeverity severity = LogSeverity.Info) { // Prepare new log entry. LogEntry logEntry = new LogEntry(); LogName logName = new LogName(projectId, logId); LogNameOneof logNameToWrite = LogNameOneof.From(logName); logEntry.LogName = logName.ToString(); logEntry.Severity = severity; // Create log entry message. string messageId = DateTime.Now.Millisecond.ToString(); string entrySeverity = logEntry.Severity.ToString().ToUpper(); logEntry.TextPayload = $"{messageId} {entrySeverity}.Logging - {message}"; MonitoredResource resource = new MonitoredResource { Type = type }; // Add log entry to collection for writing. Multiple log entries can be added. IEnumerable <LogEntry> logEntries = new LogEntry[] { logEntry }; // Write new log entry. client.WriteLogEntriesAsync(logNameToWrite, resource, entryLabels, logEntries); }
// [END update_log_sink] // [START logging_delete_log] private void DeleteLog(string logId) { var client = LoggingServiceV2Client.Create(); LogName logName = new LogName(s_projectId, logId); client.DeleteLog(LogNameOneof.From(logName), _retryAWhile); Console.WriteLine($"Deleted {logId}."); }
public StackdriverLogger(string projectId, string logId) { _client = LoggingServiceV2Client.Create(); _logName = LogNameOneof.From(new LogName(projectId, logId)); _resource = new MonitoredResource { Type = "gce_backend_service" }; }
/// <summary> /// Method to run Health Check for google Stack Driver Telemetry (not yet implemented) /// </summary> /// <param name="serviceKey"></param> /// <param name="value"></param> /// <returns></returns> public override LightHealth.HealthCheck HealthCheck(string serviceKey, string value) { try { clientV2.WriteLogEntriesAsync(LogNameOneof.From(logName), null, null, null); return(LightHealth.HealthCheck.Healthy); } catch { return(LightHealth.HealthCheck.Unhealthy); } }
/// <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>Snippet for DeleteLogAsync</summary> public async Task DeleteLogAsync() { // Snippet: DeleteLogAsync(LogNameOneof,CallSettings) // Additional: DeleteLogAsync(LogNameOneof,CancellationToken) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) LogNameOneof logName = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")); // Make the request await loggingServiceV2Client.DeleteLogAsync(logName); // End snippet }
static void Main(string[] args) { // Your Google Cloud Platform project ID. string projectId = "YOUR-PROJECT-ID"; // Instantiates a client. var client = LoggingServiceV2Client.Create(); // Prepare new log entry. LogEntry logEntry = new LogEntry(); string logId = "my-log"; LogName logName = new LogName(projectId, logId); LogNameOneof logNameToWrite = LogNameOneof.From(logName); logEntry.LogName = logName.ToString(); logEntry.Severity = LogSeverity.Info; // Create log entry message. string message = "Hello World!"; string messageId = DateTime.Now.Millisecond.ToString(); Type myType = typeof(QuickStart); string entrySeverity = logEntry.Severity.ToString().ToUpper(); logEntry.TextPayload = $"{messageId} {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 resource type 'global' causing 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 }; // Write new log entry. client.WriteLogEntries(logNameToWrite, resource, entryLabels, logEntries); Console.WriteLine("Log Entry created."); }
/// <summary>Snippet for WriteLogEntries</summary> public void WriteLogEntries() { // Snippet: WriteLogEntries(LogNameOneof,MonitoredResource,IDictionary<string, string>,IEnumerable<LogEntry>,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) LogNameOneof logName = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")); MonitoredResource resource = new MonitoredResource(); IDictionary <string, string> labels = new Dictionary <string, string>(); IEnumerable <LogEntry> entries = new List <LogEntry>(); // Make the request WriteLogEntriesResponse response = loggingServiceV2Client.WriteLogEntries(logName, resource, labels, entries); // End snippet }
/// <summary>Snippet for DeleteLog</summary> public void DeleteLog_RequestObject() { // Snippet: DeleteLog(DeleteLogRequest,CallSettings) // Create client LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create(); // Initialize request argument(s) DeleteLogRequest request = new DeleteLogRequest { LogNameAsLogNameOneof = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")), }; // Make the request loggingServiceV2Client.DeleteLog(request); // End snippet }
public GoogleCloudLoggingSink(GoogleCloudLoggingSinkOptions sinkOptions, MessageTemplateTextFormatter messageTemplateTextFormatter, int batchSizeLimit, TimeSpan period) : base(batchSizeLimit, period) { _client = LoggingServiceV2Client.Create(); _sinkOptions = sinkOptions; _resource = new MonitoredResource { Type = sinkOptions.ResourceType }; var ln = new LogName(sinkOptions.ProjectId, sinkOptions.LogName); _logName = ln.ToString(); _logNameToWrite = LogNameOneof.From(ln); _messageTemplateTextFormatter = messageTemplateTextFormatter; }
public void DeleteLog2() { Mock <LoggingServiceV2.LoggingServiceV2Client> mockGrpcClient = new Mock <LoggingServiceV2.LoggingServiceV2Client>(MockBehavior.Strict); DeleteLogRequest request = new DeleteLogRequest { LogNameAsLogNameOneof = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteLog(request, It.IsAny <CallOptions>())) .Returns(expectedResponse); LoggingServiceV2Client client = new LoggingServiceV2ClientImpl(mockGrpcClient.Object, null); client.DeleteLog(request); mockGrpcClient.VerifyAll(); }
public async Task DeleteLogAsync2() { Mock <LoggingServiceV2.LoggingServiceV2Client> mockGrpcClient = new Mock <LoggingServiceV2.LoggingServiceV2Client>(MockBehavior.Strict); DeleteLogRequest request = new DeleteLogRequest { LogNameAsLogNameOneof = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteLogAsync(request, It.IsAny <CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall <Empty>(Task.FromResult(expectedResponse), null, null, null, null)); LoggingServiceV2Client client = new LoggingServiceV2ClientImpl(mockGrpcClient.Object, null); await client.DeleteLogAsync(request); mockGrpcClient.VerifyAll(); }
public static string WriteLog( string msg, [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0, [CallerMemberName] string memberName = "") { var client = LoggingServiceV2Client.Create(); var resource = new MonitoredResource { Type = "global" }; resource.Labels["project_id"] = ProjectId; LogName logName = new LogName(ProjectId, LogId); LogEntrySourceLocation sourceLocation = new LogEntrySourceLocation { File = sourceFilePath, Line = sourceLineNumber, Function = memberName }; LogEntry logEntry = new LogEntry { LogName = logName.ToString(), Severity = LogSeverity.Info, SourceLocation = sourceLocation, TextPayload = msg }; IDictionary <string, string> entryLabels = new Dictionary <string, string> { { "size", "large" }, { "color", "red" } }; TryAddGitRevisionId(entryLabels); client.WriteLogEntries( logName: LogNameOneof.From(logName), resource: resource, labels: entryLabels, entries: new[] { logEntry }, callSettings: null); return(logEntry.ToString()); }
/// <summary>Snippet for DeleteLogAsync</summary> public async Task DeleteLogAsync_RequestObject() { // Snippet: DeleteLogAsync(DeleteLogRequest,CallSettings) // Additional: DeleteLogAsync(DeleteLogRequest,CancellationToken) // Create client LoggingServiceV2Client loggingServiceV2Client = await LoggingServiceV2Client.CreateAsync(); // Initialize request argument(s) DeleteLogRequest request = new DeleteLogRequest { LogNameAsLogNameOneof = LogNameOneof.From(new LogName("[PROJECT]", "[LOG]")), }; // Make the request await loggingServiceV2Client.DeleteLogAsync(request); // End snippet }
//TrackMetric sends to the Google Stack Driver metrics related to some point of view. //For example, you can measure how much time was spent to persist data in the database. public override void TrackMetric(string metricLabel, double value) { LogEntry logEntry = new LogEntry { LogName = metricLabel, TextPayload = value.ToString(), Timestamp = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(DateTime.Now) }; //Adding Metric log entries to send to google Cloud MonitoredResource resource = new MonitoredResource { Type = "TrackMetric" }; IDictionary <string, string> entryLabels = new Dictionary <string, string> { { "size", "large" }, { "color", "red" } }; //Send Metric Log to Google Cloud Stack Driver clientV2.WriteLogEntries(LogNameOneof.From(logName), resource, entryLabels, new[] { logEntry }); }
/// <summary> /// Not Implemented because the driver isn't implemented. /// </summary> /// <param name="metricTelemetry"></param> public override void TrackAggregateMetric(object metricTelemetry) { //Create a object to write trace log Entries LogEntry logEntry = new LogEntry { LogName = logName.ToString(), TextPayload = (string)metricTelemetry.GetType().GetProperty("Name").GetValue(metricTelemetry) + " - " + (string)metricTelemetry.GetType().GetProperty("Sum").GetValue(metricTelemetry), }; //Adding Metric log entries to send to google Cloud MonitoredResource resource = new MonitoredResource { Type = "TrackAggregateMetric" }; IDictionary <string, string> entryLabels = new Dictionary <string, string> { { "size", "large" }, { "color", "red" } }; //Send Metric Log to Google Cloud Stack Driver clientV2.WriteLogEntries(LogNameOneof.From(logName), resource, entryLabels, new[] { logEntry }); }
public void WriteLogEntry_SimpleMessage() { string logMessageFormat = "This is a log"; Debugger.V2.Breakpoint breakpoint = new Debugger.V2.Breakpoint() { LogLevel = Debugger.V2.Breakpoint.Types.LogLevel.Error, LogMessageFormat = logMessageFormat }; LogEntry logEntry = new LogEntry { LogName = _logNameObj.ToString(), Severity = Logging.Type.LogSeverity.Error, TextPayload = $"LOGPOINT: {logMessageFormat}" }; _client.WriteLogEntry(breakpoint); _mockLoggingClient.Verify(client => client.WriteLogEntries(LogNameOneof.From(_logNameObj), _resource, null, new[] { logEntry }, null), Times.Once()); }