public async Task UseGoogleDiagnostics_ConfiguresComponents()
        {
            var testId    = Utils.GetTestId();
            var startTime = DateTime.UtcNow;
            var resource  = new MonitoredResource
            {
                Type   = "global",
                Labels =
                {
                    { "project_id", Utils.GetProjectIdFromEnvironment() },
                    { "module_id",  "some-service"                      },
                    { "version_id", "1.0.0"                             },
                    { "build_id",   "some-build-id"                     }
                }
            };

            var webHostBuilder = new WebHostBuilder()
                                 .ConfigureServices(services => services.AddMvcCore())
                                 .Configure(app => app.UseMvcWithDefaultRoute())
                                 .UseGoogleDiagnostics(monitoredResource: resource);

            using (var server = new TestServer(webHostBuilder))
                using (var client = server.CreateClient())
                {
                    await TestTrace(testId, startTime, client);
                    await TestLogging(testId, startTime, client);
                    await TestErrorReporting(testId, startTime, client);
                }
        }
示例#2
0
        public void GetAndCheckServiceVersion()
        {
            var serviceVersion         = "1.0.0";
            var resourceServiceVersion = "1.0.0";
            var monitoredResource      = new MonitoredResource
            {
                Type   = "some-type",
                Labels =
                {
                    { "version_id", resourceServiceVersion }
                }
            };

            // The string service version is not null and the MonitoredResource contains a service version
            // so the string service version is returned.  We do this as the explicitly set service version should be
            // defaulted to.
            Assert.Equal(serviceVersion, Project.GetAndCheckServiceVersion(serviceVersion, monitoredResource));

            // The string service version is not null and the MonitoredResource does not contain a service version
            // so the string service version is returned.
            Assert.Equal(serviceVersion, Project.GetAndCheckServiceVersion(serviceVersion, new MonitoredResource()));

            // The string service version is null and the MonitoredResource does contains a service version
            // so the service version from the MonitoredResource is returned.
            Assert.Equal(resourceServiceVersion, Project.GetAndCheckServiceVersion(null, monitoredResource));

            // The string service version is null and the MonitoredResource does not contain a service version
            // so we throw an InvalidOperationException.
            var ex = Assert.Throws <InvalidOperationException>(() => Project.GetAndCheckServiceVersion(null, new MonitoredResource()));

            Assert.Equal("No Google App Engine service version was passed in or detected.", ex.Message);
        }
示例#3
0
        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));
        }
示例#4
0
        protected override void ProcessRecord()
        {
            string selectedType = _dynamicParameters["ResourceType"].Value.ToString().ToLower();
            MonitoredResourceDescriptor selectedDescriptor = GetResourceDescriptor(selectedType);
            IEnumerable <string>        descriptorLabels   = selectedDescriptor.Labels.Select(label => label.Key);

            // Validate that the Labels passed in match what is found in the labels of the selected descriptor.
            foreach (string labelKey in Labels.Keys)
            {
                if (!descriptorLabels.Contains(labelKey))
                {
                    string descriptorLabelsString = string.Join(", ", descriptorLabels);
                    string errorMessage           = $"Label '{labelKey}' cannot be found for monitored resource of type '{selectedType}'."
                                                    + $"The available lables are '{descriptorLabelsString}'.";
                    ErrorRecord errorRecord = new ErrorRecord(
                        new ArgumentException(errorMessage),
                        "InvalidLabel",
                        ErrorCategory.InvalidData,
                        labelKey);
                    ThrowTerminatingError(errorRecord);
                }
            }

            MonitoredResource createdResource = new MonitoredResource()
            {
                Type   = selectedType,
                Labels = ConvertToDictionary <string, string>(Labels)
            };

            WriteObject(createdResource);
        }
示例#5
0
        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);
        }
示例#6
0
        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);
        }
示例#7
0
        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;
        }
示例#8
0
        public void DoesNotCacheSpecifiedMonitoredResourceInstance()
        {
            var projectId1         = "pid-1";
            var resourceProjectId1 = "pid-1";
            var monitoredResource1 = new MonitoredResource
            {
                Type   = "some-type",
                Labels =
                {
                    { "project_id", resourceProjectId1 }
                }
            };

            Assert.Equal(projectId1, Project.GetAndCheckProjectId(null, monitoredResource1));

            // Create a second MonitoredResource instance and pass it to GetAndCheckProjectId.
            // Assert that the first MonitoredResource instance is not cached by checking if the project ID is correct.
            // Only auto-detected MonitoredResource instances should be cached.
            var projectId2         = "pid-2";
            var resourceProjectId2 = "pid-2";
            var monitoredResource2 = new MonitoredResource
            {
                Type   = "some-type",
                Labels =
                {
                    { "project_id", resourceProjectId2 }
                }
            };

            Assert.Equal(projectId2, Project.GetAndCheckProjectId(null, monitoredResource2));
        }
        public async Task UseGoogleDiagnostics_ConfiguresComponents()
        {
            var testId    = IdGenerator.FromDateTime();
            var startTime = DateTime.UtcNow;
            var resource  = new MonitoredResource
            {
                Type   = "global",
                Labels =
                {
                    { "project_id", TestEnvironment.GetTestProjectId() },
                    { "module_id",  EntryData.Service                  },
                    { "version_id", EntryData.Version                  },
                    { "build_id",   "some-build-id"                    }
                }
            };
            // We won't be able to detect the right monitored resource, so specify it explicitly.
            var loggerOptions  = LoggerOptions.Create(monitoredResource: resource);
            var webHostBuilder = new WebHostBuilder()
                                 .ConfigureServices(services => services.AddMvcCore())
                                 .Configure(app => app.UseMvcWithDefaultRoute())
                                 .UseGoogleDiagnostics(TestEnvironment.GetTestProjectId(), EntryData.Service, EntryData.Version, loggerOptions);

            using (var server = new TestServer(webHostBuilder))
                using (var client = server.CreateClient())
                {
                    await TestTrace(testId, startTime, client);
                    await TestLogging(testId, startTime, client);
                    await TestErrorReporting(testId, client);
                }
        }
示例#10
0
    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()}");
    }
示例#11
0
        public void GetAndCheckProjectId()
        {
            var projectId         = "pid";
            var resourceProjectId = "pid";
            var monitoredResource = new MonitoredResource
            {
                Type   = "some-type",
                Labels =
                {
                    { "project_id", resourceProjectId }
                }
            };

            // The string project id is not null and the MonitoredResource contains a project id
            // so the string project id is returned.  We do this as the explicitly set project id should be
            // defaulted to.
            Assert.Equal(projectId, CommonUtils.GetAndCheckProjectId(projectId, monitoredResource));

            // The string project id is not null and the MonitoredResource does not contain a project id
            // so the string project id is returned.
            Assert.Equal(projectId, CommonUtils.GetAndCheckProjectId(projectId, new MonitoredResource()));

            // The string project id is null and the MonitoredResource does contains a project id
            // so the project id from the MonitoredResource is returned.
            Assert.Equal(resourceProjectId, CommonUtils.GetAndCheckProjectId(null, monitoredResource));

            // The string project id is null and the MonitoredResource does not contain a project id
            // so we throw an InvalidOperationException.
            Assert.Throws <InvalidOperationException>(
                () => CommonUtils.GetAndCheckProjectId(null, new MonitoredResource()));
        }
示例#12
0
 /// <summary>
 /// Create a new instance of <see cref="LoggerOptions"/>.
 /// </summary>
 /// <param name="logLevel">Optional, the minimum log level.  Defaults to <see cref="LogLevel.Information"/></param>
 /// <param name="monitoredResource">Optional, the monitored resource.  Defaults to the global resource.
 ///     See: https://cloud.google.com/logging/docs/api/v2/resource-list </param>
 /// <param name="bufferOptions">Optional, the buffer options.  Defaults to a <see cref="BufferType.Sized"/></param>
 public static LoggerOptions Create(LogLevel logLevel = LogLevel.Information,
                                    MonitoredResource monitoredResource = null, BufferOptions bufferOptions = null)
 {
     monitoredResource = monitoredResource ?? GlobalResource;
     bufferOptions     = bufferOptions ?? BufferOptions.SizedBuffer();
     return(new LoggerOptions(logLevel, monitoredResource, bufferOptions));
 }
 /// <summary>
 /// Create a new instance of <see cref="LoggerOptions"/>.
 /// </summary>
 /// <param name="logLevel">Optional, the minimum log level.  Defaults to <see cref="LogLevel.Information"/></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>
 /// <param name="bufferOptions">Optional, the buffer options.  Defaults to a <see cref="BufferType.Timed"/></param>
 public static LoggerOptions Create(LogLevel logLevel = LogLevel.Information,
                                    MonitoredResource monitoredResource = null, BufferOptions bufferOptions = null)
 {
     monitoredResource = monitoredResource ?? MonitoredResourceBuilder.FromPlatform();
     bufferOptions     = bufferOptions ?? BufferOptions.TimedBuffer();
     return(new LoggerOptions(logLevel, monitoredResource, bufferOptions));
 }
        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);
        }
示例#15
0
        // [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}.");
        }
示例#16
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 }));
        }
示例#17
0
        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);
        }
示例#18
0
        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}.");
        }
 /// <summary>
 /// Creates a new instance of the <see cref="ErrorEventToLogEntryConsumer"/>.
 /// </summary>
 /// <param name="logName">The name of the log.  Not the fully qualified name. Cannot be null.</param>
 /// <param name="logTarget">Where to log, such as a project or organization. Cannot be null.</param>
 /// <param name="logConsumer">The log consumer. Cannot be null.</param>
 /// <param name="monitoredResource">The resource that is being monitored. Cannot be null.</param>
 internal ErrorEventToLogEntryConsumer(string logName, LogTarget logTarget,
                                       IConsumer <LogEntry> logConsumer, MonitoredResource monitoredResource)
 {
     GaxPreconditions.CheckNotNullOrEmpty(logName, nameof(logName));
     _logName           = GaxPreconditions.CheckNotNull(logTarget, nameof(logTarget)).GetFullLogName(logName);
     _logConsumer       = GaxPreconditions.CheckNotNull(logConsumer, nameof(logConsumer));
     _monitoredResource = GaxPreconditions.CheckNotNull(monitoredResource, nameof(monitoredResource));
 }
 public StackdriverLogger(string projectId, string logId)
 {
     _client   = LoggingServiceV2Client.Create();
     _logName  = LogNameOneof.From(new LogName(projectId, logId));
     _resource = new MonitoredResource {
         Type = "gce_backend_service"
     };
 }
示例#21
0
        public void CreateTimeSeries()
        {
            ProjectName name = new ProjectName(projectId);

            // Prepare a data point.
            Point      dataPoint  = new Point();
            TypedValue salesTotal = new TypedValue
            {
                DoubleValue = 123.45
            };

            dataPoint.Value = salesTotal;
            // Sets data point's interval end time to current time.
            Timestamp timeStamp = new Timestamp();
            DateTime  UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            timeStamp.Seconds = (long)(DateTime.UtcNow - UnixEpoch).TotalSeconds;
            TimeInterval interval = new TimeInterval
            {
                EndTime = timeStamp
            };

            dataPoint.Interval = interval;

            // Prepare custom metric.
            Metric metric = new Metric
            {
                Type = "custom.googleapis.com/shops/daily_sales"
            };

            metric.Labels.Add("store_id", "Pittsburgh");

            // Prepare monitored resource.
            MonitoredResource resource = new MonitoredResource
            {
                Type = "global"
            };

            resource.Labels.Add("project_id", projectId);

            // Create a new time series using inputs.
            TimeSeries timeSeriesData = new TimeSeries
            {
                Metric   = metric,
                Resource = resource
            };

            timeSeriesData.Points.Add(dataPoint);

            // Add newly created time series to list of time series to be written.
            IEnumerable <TimeSeries> timeSeries = new List <TimeSeries> {
                timeSeriesData
            };

            // Write time series data.
            client.CreateTimeSeriesAsync(name, timeSeries);
        }
 private LoggerOptions(
     LogLevel logLevel, Dictionary <string, string> labels,
     MonitoredResource monitoredResource, BufferOptions bufferOptions)
 {
     LogLevel          = GaxPreconditions.CheckEnumValue(logLevel, nameof(logLevel));
     Labels            = labels;
     MonitoredResource = monitoredResource;
     BufferOptions     = bufferOptions;
 }
 /// <summary>
 /// Create a new instance of <see cref="LoggerOptions"/>.
 /// </summary>
 /// <param name="logLevel">Optional, the minimum log level.  Defaults to <see cref="LogLevel.Information"/></param>
 /// <param name="labels">Optional, custom labels to be added to log entries.</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>
 /// <param name="bufferOptions">Optional, the buffer options.  Defaults to a <see cref="BufferType.Timed"/></param>
 public static LoggerOptions Create(LogLevel logLevel = LogLevel.Information,
                                    Dictionary <string, string> labels  = null,
                                    MonitoredResource monitoredResource = null, BufferOptions bufferOptions = null)
 {
     labels            = labels ?? new Dictionary <string, string>();
     monitoredResource = monitoredResource ?? MonitoredResourceBuilder.FromPlatform();
     bufferOptions     = bufferOptions ?? BufferOptions.TimedBuffer();
     return(new LoggerOptions(logLevel, labels, monitoredResource, bufferOptions));
 }
 /// <summary>
 /// Writes log entries to Stackdriver Logging.  All log entries are
 /// written by this method.
 /// </summary>
 /// <param name="logName">
 /// Optional. A default log resource name for those log entries in `entries`
 /// that do not specify their own `logName`.  Example:
 /// `"projects/my-project/logs/syslog"`.  See
 /// [LogEntry][google.logging.v2.LogEntry].
 /// </param>
 /// <param name="resource">
 /// Optional. A default monitored resource for those log entries in `entries`
 /// that do not specify their own `resource`.
 /// </param>
 /// <param name="labels">
 /// Optional. User-defined `key:value` items that are added to
 /// the `labels` field of each log entry in `entries`, except when a log
 /// entry specifies its own `key:value` item with the same key.
 /// Example: `{ "size": "large", "color":"red" }`
 /// </param>
 /// <param name="entries">
 /// Required. The log entries to write. The log entries must have values for
 /// all required fields.
 ///
 /// To improve throughput and to avoid exceeding the quota limit for calls
 /// to `entries.write`, use this field to write multiple log entries at once
 /// rather than  // calling this method for each log entry.
 /// </param>
 /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
 /// <returns>The RPC response.</returns>
 public virtual WriteLogEntriesResponse WriteLogEntries(
     string logName,
     MonitoredResource resource,
     IDictionary <string, string> labels,
     IEnumerable <LogEntry> entries,
     CallSettings callSettings = null)
 {
     throw new NotImplementedException();
 }
示例#25
0
 /// <summary>
 /// Create a new instance of <see cref="LoggerOptions"/>.
 /// </summary>
 /// <param name="logLevel">Optional, the minimum log level.  Defaults to <see cref="LogLevel.Information"/></param>
 /// <param name="logName">Optional, the name of the log.  Defaults to 'aspnetcore'.</param>
 /// <param name="labels">Optional, custom labels to be added to log entries.
 /// Keys and values added to <paramref name="labels"/> should not be null.
 /// If they are, an exception will be throw when attempting to log an entry.
 /// The entry won't be logged and the exception will be propagated depending
 /// on the value of <see cref="RetryOptions.ExceptionHandling"/>.</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>
 /// <param name="bufferOptions">Optional, the buffer options.  Defaults to a <see cref="BufferType.Timed"/></param>
 /// <param name="retryOptions">Optional, the retry options.  Defaults to a <see cref="RetryType.None"/></param>
 /// <param name="loggerDiagnosticsOutput">Optional. If set some logger diagnostics info will be written
 /// to the given <see cref="TextWriter"/>. Currently the only diagnostics info we provide is the URL where
 /// the logs written with these options can be found.</param>
 public static LoggerOptions Create(
     LogLevel logLevel = LogLevel.Information,
     string logName    = null,
     Dictionary <string, string> labels  = null,
     MonitoredResource monitoredResource = null,
     BufferOptions bufferOptions         = null,
     RetryOptions retryOptions           = null,
     TextWriter loggerDiagnosticsOutput  = null) =>
 CreateWithServiceContext(logLevel, logName, labels, monitoredResource, bufferOptions, retryOptions, loggerDiagnosticsOutput);
 /// <summary>
 /// Writes log entries to Cloud Logging.
 /// All log entries in Cloud Logging are written by this method.
 /// </summary>
 /// <param name="log_name">
 /// Optional. A default log resource name for those log entries in `entries`
 /// that do not specify their own `logName`.  Example:
 /// `"projects/my-project/logs/syslog"`.  See
 /// [LogEntry][google.logging.v2.LogEntry].
 /// </param>
 /// <param name="resource">
 /// Optional. A default monitored resource for those log entries in `entries`
 /// that do not specify their own `resource`.
 /// </param>
 /// <param name="labels">
 /// Optional. User-defined `key:value` items that are added to
 /// the `labels` field of each log entry in `entries`, except when a log
 /// entry specifies its own `key:value` item with the same key.
 /// Example: `{ "size": "large", "color":"red" }`
 /// </param>
 /// <param name="entries">
 /// Required. The log entries to write. The log entries must have values for
 /// all required fields.
 /// </param>
 /// <param name="cancellationToken">If not null, a <see cref="CancellationToken"/> to use for this RPC.</param>
 /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
 /// <returns>A Task containing the RPC response.</returns>
 public virtual Task <WriteLogEntriesResponse> WriteLogEntriesAsync(
     string logName,
     MonitoredResource resource,
     IDictionary <string, string> labels,
     IEnumerable <LogEntry> entries,
     CancellationToken?cancellationToken = null,
     CallSettings callSettings           = null)
 {
     throw new NotImplementedException();
 }
示例#27
0
        public static void Main(string[] args)
        {
            // Your Google Cloud Platform project ID.
            string projectId = "YOUR-PROJECT-ID";

            // Create client.
            MetricServiceClient metricServiceClient = MetricServiceClient.Create();

            // Initialize request argument(s).
            ProjectName name = new ProjectName(projectId);

            // Prepare a data point.
            Point      dataPoint  = new Point();
            TypedValue salesTotal = new TypedValue();

            salesTotal.DoubleValue = 123.45;
            dataPoint.Value        = salesTotal;
            // Sets data point's interval end time to current time.
            Timestamp timeStamp = new Timestamp();
            DateTime  UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            timeStamp.Seconds = (long)(DateTime.UtcNow - UnixEpoch).TotalSeconds;
            TimeInterval interval = new TimeInterval();

            interval.EndTime   = timeStamp;
            dataPoint.Interval = interval;

            // Prepare custom metric.
            Metric metric = new Metric();

            metric.Type = "custom.googleapis.com/stores/daily_sales";
            metric.Labels.Add("store_id", "Pittsburgh");

            // Prepare monitored resource.
            MonitoredResource resource = new MonitoredResource();

            resource.Type = "global";
            resource.Labels.Add("project_id", projectId);

            // Create a new time series using inputs.
            TimeSeries timeSeriesData = new TimeSeries();

            timeSeriesData.Metric   = metric;
            timeSeriesData.Resource = resource;
            timeSeriesData.Points.Add(dataPoint);

            // Add newly created time series to list of time series to be written.
            IEnumerable <TimeSeries> timeSeries = new List <TimeSeries> {
                timeSeriesData
            };

            // Write time series data.
            metricServiceClient.CreateTimeSeries(name, timeSeries);
            Console.WriteLine("Done writing time series data.");
        }
示例#28
0
        private static MonitoredResource GetResourceType()
        {
            var resource = new MonitoredResource {
                Type = "gce_instance"
            };

            resource.Labels["instance_id"] = s_instanceId.Value.ToString();
            resource.Labels["project_id"]  = _projectId;
            resource.Labels["zone"]        = s_instance.Value.Zone.ToString();
            return(resource);
        }
        public void GetGcpConsoleLogsUrl_GkeContainerToContainer()
        {
            var resource = new MonitoredResource
            {
                Type = "gke_container"
            };
            GoogleLogger logger = GetLogger(monitoredResource: resource);
            string       query  = logger.GetGcpConsoleLogsUrl().Query;

            Assert.Contains($"resource=container", query);
        }
示例#30
0
        private static string GetServiceVersionFromResource(MonitoredResource resource)
        {
            switch (resource?.Type)
            {
            case "gae_app": return(GetLabel(resource, "version_id"));

            case "cloud_run_revision": return(GetLabel(resource, "revision_name"));

            default: return(null);
            }
        }
        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.");
        }
        protected override void ProcessRecord()
        {
            LogName = PrefixProject(LogName, Project);
            if (MonitoredResource == null)
            {
                MonitoredResource = new MonitoredResource()
                {
                    Type = "global",
                    Labels = new Dictionary<string, string>() { { "project_id", Project } }
                };
            }
            List<LogEntry> entries = new List<LogEntry>();

            switch (ParameterSetName)
            {
                case ParameterSetNames.TextPayload:
                    foreach (string text in TextPayload)
                    {
                        LogEntry entry = new LogEntry()
                        {
                            LogName = LogName,
                            Severity = Enum.GetName(typeof(LogSeverity), Severity),
                            Resource = MonitoredResource,
                            TextPayload = text
                        };
                        entries.Add(entry);
                    }
                    break;
                case ParameterSetNames.ProtoPayload:
                    foreach (Hashtable hashTable in ProtoPayload)
                    {
                        LogEntry entry = new LogEntry()
                        {
                            LogName = LogName,
                            Severity = Enum.GetName(typeof(LogSeverity), Severity),
                            Resource = MonitoredResource,
                            ProtoPayload = ConvertToDictionary<string, object>(hashTable)
                        };
                        entries.Add(entry);
                    }
                    break;
                case ParameterSetNames.JsonPayload:
                    foreach (Hashtable hashTable in JsonPayload)
                    {
                        LogEntry entry = new LogEntry()
                        {
                            LogName = LogName,
                            Severity = Enum.GetName(typeof(LogSeverity), Severity),
                            Resource = MonitoredResource,
                            JsonPayload = ConvertToDictionary<string, object>(hashTable)
                        };
                        entries.Add(entry);
                    }
                    break;
                default:
                    throw UnknownParameterSetException;
            }

            WriteLogEntriesRequest writeRequest = new WriteLogEntriesRequest()
            {
                Entries = entries,
                LogName = LogName,
                Resource = MonitoredResource
            };
            EntriesResource.WriteRequest request = Service.Entries.Write(writeRequest);
            WriteLogEntriesResponse response = request.Execute();
        }
        protected override void ProcessRecord()
        {
            string selectedType = _dynamicParameters["ResourceType"].Value.ToString().ToLower();
            MonitoredResourceDescriptor selectedDescriptor = GetResourceDescriptor(selectedType);
            IEnumerable<string> descriptorLabels = selectedDescriptor.Labels.Select(label => label.Key);

            // Validate that the Labels passed in match what is found in the labels of the selected descriptor.
            foreach (string labelKey in Labels.Keys)
            {
                if (!descriptorLabels.Contains(labelKey))
                {
                    string descriptorLabelsString = string.Join(", ", descriptorLabels);
                    string errorMessage = $"Label '{labelKey}' cannot be found for monitored resource of type '{selectedType}'."
                        + $"The available lables are '{descriptorLabelsString}'.";
                    ErrorRecord errorRecord = new ErrorRecord(
                        new ArgumentException(errorMessage),
                        "InvalidLabel",
                        ErrorCategory.InvalidData,
                        labelKey);
                    ThrowTerminatingError(errorRecord);
                }
            }

            MonitoredResource createdResource = new MonitoredResource()
            {
                Type = selectedType,
                Labels = ConvertToDictionary<string, string>(Labels)
            };
            WriteObject(createdResource);
        }
 // [START write_log_entry]
 private void WriteLogEntry(string logId, string message)
 {
     var client = LoggingServiceV2Client.Create();
     LogName logName = new LogName(s_projectId, logId);
     LogEntry logEntry = new LogEntry
     {
         LogName = logName.ToString(),
         Severity = LogSeverity.Info,
         TextPayload = $"{typeof(LoggingSample).FullName} - {message}"
     };
     MonitoredResource resource = new MonitoredResource { Type = "global" };
     IDictionary<string, string> entryLabels = new Dictionary<string, string>
     {
         { "size", "large" },
         { "color", "red" }
     };
     client.WriteLogEntries(LogNameOneof.From(logName), resource, entryLabels,
         new[] { logEntry }, RetryAWhile);
     Console.WriteLine($"Created log entry in log-id: {logId}.");
 }