Esempio n. 1
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);
        }
Esempio n. 2
0
        /// <summary>
        /// Writes a single "canary" log entry and waits for it to be visible. This is written
        /// after all the entries from tests, so by the time this is visible, it's "reasonably likely"
        /// that all the test log messages are also visible.
        /// </summary>
        private void LogCanaryMessageAndWait()
        {
            DateTime startTime = DateTime.UtcNow;
            string   id        = IdGenerator.FromGuid();
            LogEntry entry     = new LogEntry
            {
                Resource    = MonitoredResourceBuilder.FromPlatform(),
                LogName     = $"projects/{_projectId}/logs/aspnetcore",
                Severity    = Logging.Type.LogSeverity.Info,
                Timestamp   = Timestamp.FromDateTime(DateTime.UtcNow),
                JsonPayload = new Struct {
                    Fields = { ["message"] = Value.ForString(id) }
                }
            };

            _client.WriteLogEntries((LogName)null, null, null, new[] { entry });

            var request = BuildRequest(startTime);

            request.Filter += $" AND jsonPayload.message:\"{id}\"";

            // Wait for the canary log entry to be visible.
            var endTime = startTime + s_canaryMessageTimeout;

            while (DateTime.UtcNow < endTime)
            {
                FileLogger.Log("Listing log entries to find the canary");
                if (_client.ListLogEntries(request).Any())
                {
                    return;
                }
                Thread.Sleep(s_delayBetweenCanaryAttempts);
            }
            throw new Exception("Canary message never seen.");
        }
Esempio n. 3
0
        public void WriteLog(LogSeverity logSeverity, string message, string description = null)
        {
            try
            {
                LogEntry logEntry = new LogEntry
                {
                    LogName     = logName.ToString(),
                    Severity    = logSeverity,
                    TextPayload = message,
                    JsonPayload = GetJsonPayload(message, description)
                };

                IDictionary <string, string> entryLabels = new Dictionary <string, string>
                {
                    { "Version", Configuration.AppVersion },
                    { "Environment", Configuration.Environment.ToString() },
                    { "Channel", Configuration.BasicConfiguration.Channel },
                    { "Prefix", Configuration.BasicConfiguration.Prefix.ToString() },
                    { "MessageSpeed", Configuration.BasicConfiguration.MessageSpeed.ToString() },
                    { "TTS_Enabled", Configuration.TextToSpeechEnabled.ToString() },
                    { "TTS_Delay", Configuration.TextToSpeechDelay.ToString() },
                    { "MachineName", Environment.MachineName },
                    { "UserDomainName", Environment.UserDomainName },
                    { "UserName", Environment.UserName }
                };

                client.WriteLogEntries(logName, monitoredResource, entryLabels, new[] { logEntry });
            }
            catch (Exception)
            {
                // Leave empty
            }
        }
Esempio n. 4
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 }));
        }
Esempio n. 5
0
 /// <inheritdoc />
 public void Receive(IEnumerable <LogEntry> logs)
 {
     GaxPreconditions.CheckNotNull(logs, nameof(logs));
     if (!logs.Any())
     {
         return;
     }
     _client.WriteLogEntries(null, null, EmptyDictionary, logs);
 }
        /// <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 });
        }
 /// <summary>Snippet for WriteLogEntries</summary>
 public void WriteLogEntries_RequestObject()
 {
     // Snippet: WriteLogEntries(WriteLogEntriesRequest,CallSettings)
     // Create client
     LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create();
     // Initialize request argument(s)
     WriteLogEntriesRequest request = new WriteLogEntriesRequest
     {
         Entries = { },
     };
     // Make the request
     WriteLogEntriesResponse response = loggingServiceV2Client.WriteLogEntries(request);
     // End snippet
 }
 /// <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
 }
        private void LogMessage(string message, LogSeverity severity)
        {
            var logEntry = new LogEntry
            {
                LogName     = logName.ToString(),
                Severity    = severity,
                TextPayload = message
            };

            var resource = new Google.Api.MonitoredResource {
                Type = "gae_app"
            };

            client.WriteLogEntries(
                LogNameOneof.From(logName),
                resource,
                new Dictionary <string, string>
            {
                { "project_id", projectID }
            },
                new[] { logEntry });
        }
Esempio n. 10
0
        private static void log(String message, LogSeverity severity)
        {
            message = $"{DateTime.Now:HH:mm:ss} {severity} - {message}";

            Console.WriteLine(message);

            if (!Config.isLocal())
            {
                var logName  = new LogName(Config.googleProject, Config.environment + "-updater");
                var resource = new MonitoredResource {
                    Type = "project"
                };
                var logEntry = new LogEntry
                {
                    LogName     = logName.ToString(),
                    Severity    = severity,
                    TextPayload = message
                };

                logEntry.Labels.Add("env", Config.environment);

                googleCLient.WriteLogEntries(LogNameOneof.From(logName), resource, null, new[] { logEntry });
            }
        }
Esempio n. 11
0
        /// <summary>
        ///
        /// <para>WriteLogs:</para>
        ///
        /// <para>Writes logs to the logging service</para>
        ///
        /// <para>Check <seealso cref="IBLoggingServiceInterface.WriteLogs"/> for detailed documentation</para>
        ///
        /// </summary>
        public bool WriteLogs(
            List <BLoggingParametersStruct> _Messages,
            string _LogGroupName,
            string _LogStreamName,
            bool _bAsync = true,
            Action <string> _ErrorMessageAction = null)
        {
            if (_Messages == null || _Messages.Count == 0)
            {
                return(false);
            }

            if (_bAsync)
            {
                BTaskWrapper.Run(() =>
                {
                    WriteLogs(_Messages, _LogGroupName, _LogStreamName, false, _ErrorMessageAction);
                });
                return(true);
            }
            else
            {
                if (!BUtility.CalculateStringMD5(DateTime.Now.Subtract(DateTime.MinValue.AddYears(1969)).TotalMilliseconds.ToString(), out string Timestamp, _ErrorMessageAction))
                {
                    _ErrorMessageAction?.Invoke("BLoggingServiceGC->WriteLogs: Timestamp generation has failed.");
                    return(false);
                }

                _LogGroupName  = BUtility.EncodeStringForTagging(_LogGroupName);
                _LogStreamName = BUtility.EncodeStringForTagging(_LogStreamName);

                string StreamIDBase = _LogGroupName + "-" + _LogStreamName + "-" + Timestamp;
                try
                {
                    var LogEntries = new LogEntry[_Messages.Count];

                    int i = 0;
                    foreach (var Message in _Messages)
                    {
                        LogEntries[i] = new LogEntry
                        {
                            LogName     = new LogName(ProjectID, StreamIDBase + "-" + (i + 1).ToString()).ToString(),
                            TextPayload = Message.Message
                        };

                        switch (Message.LogType)
                        {
                        case EBLoggingServiceLogType.Debug:
                            LogEntries[i].Severity = LogSeverity.Debug;
                            break;

                        case EBLoggingServiceLogType.Info:
                            LogEntries[i].Severity = LogSeverity.Info;
                            break;

                        case EBLoggingServiceLogType.Warning:
                            LogEntries[i].Severity = LogSeverity.Warning;
                            break;

                        case EBLoggingServiceLogType.Error:
                            LogEntries[i].Severity = LogSeverity.Error;
                            break;

                        case EBLoggingServiceLogType.Critical:
                            LogEntries[i].Severity = LogSeverity.Critical;
                            break;
                        }

                        i++;
                    }

                    LoggingServiceClient.WriteLogEntries(
                        LogNameOneof.From(new LogName(ProjectID, StreamIDBase)),
                        ResourceName,
                        new Dictionary <string, string>()
                    {
                        ["LogGroup"]  = _LogGroupName,
                        ["LogStream"] = _LogStreamName
                    },
                        LogEntries);

                    return(true);
                }
                catch (Exception e)
                {
                    _ErrorMessageAction?.Invoke("BLoggingServiceGC->WriteLogs: " + e.Message + ", Trace: " + e.StackTrace);
                }
            }
            return(false);
        }