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 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) LogName logName = LogName.FromProjectLog(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); }
internal string GET_Parsed_Sysmon_EventData() { string Parsed_Sysmon_String = ""; if (LogName.ToLower().Equals("microsoft-windows-sysmon/operational") && (Settings.AppConfig_File_Args.ContainsKey(Settings.SWELF_AppConfig_Args[18]) && Settings.AppConfig_File_Args[Settings.SWELF_AppConfig_Args[18]].ToLower() == "true")) { string[] Data = EventData.Split(new[] { "\r\n" }, StringSplitOptions.None).ToArray(); for (int x = 0; x < Data.Length; ++x) { int index = Data[x].IndexOf(':'); string first = Data[x].Substring(0, index); string second = Data[x].Substring(index + 1); if (string.IsNullOrEmpty(second)) { second = ""; } if (second.Length > 0 && char.IsWhiteSpace(second.ElementAt(0))) { second = second.Trim(); } Parsed_Sysmon_String += first + "=" + "\"" + second + "\"" + "\t"; } } return(Parsed_Sysmon_String.Trim()); }
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); }
public void WriteLogEntriesResourceNames() { moq::Mock <LoggingServiceV2.LoggingServiceV2Client> mockGrpcClient = new moq::Mock <LoggingServiceV2.LoggingServiceV2Client>(moq::MockBehavior.Strict); WriteLogEntriesRequest request = new WriteLogEntriesRequest { LogNameAsLogName = LogName.FromProjectLog("[PROJECT]", "[LOG]"), Resource = new ga::MonitoredResource(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Entries = { new LogEntry(), }, }; WriteLogEntriesResponse expectedResponse = new WriteLogEntriesResponse { }; mockGrpcClient.Setup(x => x.WriteLogEntries(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(expectedResponse); LoggingServiceV2Client client = new LoggingServiceV2ClientImpl(mockGrpcClient.Object, null); WriteLogEntriesResponse response = client.WriteLogEntries(request.LogNameAsLogName, request.Resource, request.Labels, request.Entries); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); }
private string GET_Sysmon_Netwrok_Calling_Process_Name_Dst_Port() { try { string Eventdata = Compression_Operation.DeCompress_Contents_String(EVT_Data_Compressed, EVT_Data_Size); if (Eventdata.Contains("destinationport: ") && LogName.ToLower().Equals("microsoft-windows-sysmon/operational") && EventID == 3) { string[] delm1 = { "destinationport: ", "destinationportname: " }; string[] datA = Eventdata.Split(delm1, StringSplitOptions.RemoveEmptyEntries).ToArray(); if (datA[1].Length > 0 && (!string.IsNullOrEmpty(datA[1]))) { Sysmon_DST_Port = datA[1].Replace("\r\n", ""); } } Eventdata = null; return(Sysmon_DST_Port); } catch (Exception e) { return(Sysmon_DST_Port = ""); } }
private string GET_Sysmon_Network_Process_Name() { try { string Eventdata = Compression_Operation.DeCompress_Contents_String(EVT_Data_Compressed, EVT_Data_Size); if (Eventdata.Contains("image: ") && LogName.ToLower().Equals("microsoft-windows-sysmon/operational") && EventID == 3) { string[] delm1 = { "image: ", "user: "******"\r\n", ""); } } Eventdata = null; return(Sysmon_Src_Process); } catch (Exception e) { return(Sysmon_Src_Process = ""); } }
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); }
internal void GET_HostName_FromLogFile() { string Eventdata = Compression_Operation.DeCompress_Contents_String(EVT_Data_Compressed, EVT_Data_Size); List <string> EventlogDataSegment = Eventdata.Split(Settings.EventLogEntry_splitter, StringSplitOptions.RemoveEmptyEntries).ToList(); EventlogDataSegment = EventlogDataSegment.Distinct().ToList(); EventlogDataSegment.Sort(); if (Settings.AppConfig_File_Args.ContainsKey(Settings.SWELF_AppConfig_Args[11])) { foreach (string line in EventlogDataSegment) { if (Eventdata.Contains("destinationhostname: ") && LogName.ToLower().Equals("microsoft-windows-sysmon/operational") && EventID == 3) { string[] delm1 = { "destinationhostname: ", "destinationhostname: " }; string[] datA = Eventdata.Split(delm1, StringSplitOptions.RemoveEmptyEntries).ToArray(); if (datA[1].Length > 0 && (!string.IsNullOrEmpty(datA[1]))) { //add hostname } } else if (Settings.Hostname_RegX.IsMatch(line) && line.Contains('.') && line.Contains('\\') == false && string.IsNullOrEmpty(line) == false) { //add hostname } } } EventlogDataSegment.Clear(); Eventdata = null; }
public override int GetHashCode() { int hash = 1; if (LogName.Length != 0) { hash ^= LogName.GetHashCode(); } if (grpcService_ != null) { hash ^= GrpcService.GetHashCode(); } if (bufferFlushInterval_ != null) { hash ^= BufferFlushInterval.GetHashCode(); } if (bufferSizeBytes_ != null) { hash ^= BufferSizeBytes.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
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 async stt::Task WriteLogEntriesResourceNamesAsync() { moq::Mock <LoggingServiceV2.LoggingServiceV2Client> mockGrpcClient = new moq::Mock <LoggingServiceV2.LoggingServiceV2Client>(moq::MockBehavior.Strict); WriteLogEntriesRequest request = new WriteLogEntriesRequest { LogNameAsLogName = LogName.FromProjectLog("[PROJECT]", "[LOG]"), Resource = new ga::MonitoredResource(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Entries = { new LogEntry(), }, }; WriteLogEntriesResponse expectedResponse = new WriteLogEntriesResponse { }; mockGrpcClient.Setup(x => x.WriteLogEntriesAsync(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall <WriteLogEntriesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LoggingServiceV2Client client = new LoggingServiceV2ClientImpl(mockGrpcClient.Object, null); WriteLogEntriesResponse responseCallSettings = await client.WriteLogEntriesAsync(request.LogNameAsLogName, request.Resource, request.Labels, request.Entries, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); WriteLogEntriesResponse responseCancellationToken = await client.WriteLogEntriesAsync(request.LogNameAsLogName, request.Resource, request.Labels, request.Entries, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); }
// [END logging_list_log_entries] // [START logging_create_sink] private void CreateSink(string sinkId, string logId) { var sinkClient = ConfigServiceV2Client.Create(); CreateSinkRequest sinkRequest = new CreateSinkRequest(); LogSink myLogSink = new LogSink(); myLogSink.Name = sinkId; // This creates a sink using a Google Cloud Storage bucket // named the same as the projectId. // This requires editing the bucket's permissions to add the Entity Group // named '*****@*****.**' with 'Owner' access for the bucket. // If this is being run with a Google Cloud service account, // that account will need to be granted 'Owner' access to the Project. // In Powershell, use this command: // PS > Add-GcsBucketAcl <your-bucket-name> -Role OWNER -Group [email protected] myLogSink.Destination = "storage.googleapis.com/" + s_projectId; LogName logName = new LogName(s_projectId, logId); myLogSink.Filter = $"logName={logName.ToString()}AND severity<=ERROR"; ProjectName projectName = new ProjectName(s_projectId); sinkRequest.Sink = myLogSink; sinkClient.CreateSink(projectName, myLogSink, _retryAWhile); Console.WriteLine($"Created sink: {sinkId}."); }
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}."); }
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 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 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)); }
// Module defining this command // Optional custom code for this activity /// <summary> /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. /// </summary> /// <param name="context">The NativeActivityContext for the currently running activity.</param> /// <returns>A populated instance of System.Management.Automation.PowerShell</returns> /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks> protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context) { System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create(); System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments if (LogName.Expression != null) { targetCommand.AddParameter("LogName", LogName.Get(context)); } if (Source.Expression != null) { targetCommand.AddParameter("Source", Source.Get(context)); } if (GetIsComputerNameSpecified(context) && (PSRemotingBehavior.Get(context) == RemotingBehavior.Custom)) { targetCommand.AddParameter("ComputerName", PSComputerName.Get(context)); } return(new ActivityImplementationContext() { PowerShellInstance = invoker }); }
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 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); }
// [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}."); }
public override int GetHashCode() { unchecked { var hashCode = (Payload != null ? Payload.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (LogName != null ? LogName.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (TargetApplicationName != null ? TargetApplicationName.GetHashCode() : 0); hashCode = (hashCode * 397) ^ TargetApplicationVersion.GetHashCode(); return(hashCode); } }
internal override void ToString(List <object> targets) { if (LogName == EventLog.Application) { targets.Add($"Log: {LogName.GetDescription()}, Source: {EventSource}, Type: {EventType}"); } else { targets.Add($"Log: {LogName.GetDescription()}, Type: {EventType}"); } }
// [END logging_list_sinks] // [START logging_update_sink] private void UpdateSinkLog(string sinkId, string logId) { var sinkClient = ConfigServiceV2Client.Create(); LogName logName = new LogName(s_projectId, logId); LogSinkName sinkName = new LogSinkName(s_projectId, sinkId); var sink = sinkClient.GetSink(sinkName, _retryAWhile); sink.Filter = $"logName={logName.ToString()}AND severity<=ERROR"; sinkClient.UpdateSink(sinkName, sink, _retryAWhile); Console.WriteLine($"Updated {sinkId} to export logs from {logId}."); }
public override int GetHashCode() { var hashCode = 17; hashCode = hashCode * 23 + (EndpointId?.GetHashCode() ?? 0); hashCode = hashCode * 23 + (LogName?.GetHashCode() ?? 0); foreach (var cause in Causes) { hashCode = (hashCode * 23) ^ cause.GetHashCode(); } return(hashCode); }
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" }; }
// [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()}"); } }
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."); }
private void ActivateLogIdAndResource(string logId) { // Project ID of the project where the resource that is being monitored lives. string monitoredProjectId = null; // Project ID of the project where the entries are to be written. string targetProjectId = null; MonitoredResource resource = null; if (!DisableResourceTypeDetection) { resource = MonitoredResourceBuilder.FromPlatform(_platform); resource.Labels.TryGetValue("project_id", out monitoredProjectId); } targetProjectId = ProjectId?.Render(LogEventInfo.CreateNullEvent()); if (monitoredProjectId == null) { // Either platform detection is disabled, or it detected an unknown platform. // So use the manually configured projectId and override the resource. monitoredProjectId = GaxPreconditions.CheckNotNull(targetProjectId, nameof(ProjectId)); if (ResourceType == null) { resource = new MonitoredResource { Type = "global", Labels = { { "project_id", monitoredProjectId } } }; } else { resource = new MonitoredResource { Type = ResourceType, Labels = { ResourceLabels.ToDictionary(x => x.Name, x => x.Layout.Render(LogEventInfo.CreateNullEvent())) } }; } } if (targetProjectId == null) { // If there was no configured projectId, then use the same as the monitored resoure. targetProjectId = monitoredProjectId; } _resource = resource; var logName = new LogName(targetProjectId, logId); _logName = logName.ToString(); _logNameToWrite = logName; _traceResourcePath = !string.IsNullOrEmpty(targetProjectId) ? $"projects/{targetProjectId}/traces/" : null; }
public void Configure(float _sendingPeriod, LogName _logToWrite) { sendingPeriod = _sendingPeriod; logToWrite = _logToWrite; typesTransformArray = Constants.SubsetOfTransformDataTypes(logToWrite); if (typesTransformArray == null) { Debug.LogError("Movement can only be stored in LogName.TransformXXXX. Please change the logToWrite from `MovementRecorder`."); return; } // Flag isConfigured = true; }
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."); }
// [END update_log_sink] // [START 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}."); }
// [END list_log_entries] // [START create_log_sink] private void CreateSink(string sinkId, string logId) { var sinkClient = ConfigServiceV2Client.Create(); CreateSinkRequest sinkRequest = new CreateSinkRequest(); LogSink myLogSink = new LogSink(); myLogSink.Name = sinkId; // This creates a sink using a Google Cloud Storage bucket // named the same as the projectId. // This requires editing the bucket's permissions to add the Entity Group // named '*****@*****.**' with 'Owner' access for the bucket. // If this is being run with a Google Cloud service account, // that account will need to be granted 'Owner' access to the Project. // In Powershell, use this command: // PS > Add-GcsBucketAcl <your-bucket-name> -Role OWNER -Group [email protected] myLogSink.Destination = "storage.googleapis.com/" + s_projectId; LogName logName = new LogName(s_projectId, logId); myLogSink.Filter = $"logName={logName.ToString()}AND severity<=ERROR"; ProjectName projectName = new ProjectName(s_projectId); sinkRequest.Sink = myLogSink; sinkClient.CreateSink(ParentNameOneof.From(projectName), myLogSink, RetryAWhile); Console.WriteLine($"Created sink: {sinkId}."); }
// [END write_log_entry] // [START 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); IEnumerable<string> projectIds = new string[] { projectName.ToString() }; var results = client.ListLogEntries(projectIds, $"logName={logName.ToString()}", "timestamp desc", callSettings: RetryAWhile); foreach (var row in results) { if (row != null && !String.IsNullOrEmpty(row.TextPayload.Trim())) { Console.WriteLine($"{row.TextPayload.Trim()}"); } else { results.GetEnumerator().Dispose(); break; } } }
// [END list_log_sinks] // [START update_log_sink] private void UpdateSinkLog(string sinkId, string logId) { var sinkClient = ConfigServiceV2Client.Create(); LogName logName = new LogName(s_projectId, logId); SinkName sinkName = new SinkName(s_projectId, sinkId); var sink = sinkClient.GetSink(SinkNameOneof.From(sinkName), RetryAWhile); sink.Filter = $"logName={logName.ToString()}AND severity<=ERROR"; sinkClient.UpdateSink(SinkNameOneof.From(sinkName), sink, RetryAWhile); Console.WriteLine($"Updated {sinkId} to export logs from {logId}."); }
// [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}."); }