- 2026-04-28 1.1.11 Se añade log del sistema a tsNotificacionesClient

This commit is contained in:
2026-04-28 14:43:27 +02:00
parent 1c8df57507
commit 4b476081f5
2 changed files with 109 additions and 19 deletions

View File

@@ -5,9 +5,29 @@ Imports System.Net.Http
Imports System.Net.Http.Headers Imports System.Net.Http.Headers
Imports System.Net.Http.Json Imports System.Net.Http.Json
Imports Microsoft.Extensions.Configuration Imports Microsoft.Extensions.Configuration
Imports Microsoft.Extensions.Logging
Imports System.Diagnostics
Public Class TsNotificacionesClient Public Class TsNotificacionesClient
' ============================================================
' LOGGER MULTIPLATAFORMA (Windows → EventLog, Linux → journald)
' ============================================================
Private NotInheritable Class LogProvider
Private Shared ReadOnly _factory As ILoggerFactory = LoggerFactory.Create(
Sub(builder)
builder.AddConsole() ' Linux → journald
builder.AddEventLog() ' Windows → Event Viewer
End Sub)
Public Shared Function CreateLogger(Of T)() As ILogger(Of T)
Return _factory.CreateLogger(Of T)()
End Function
End Class
' ============================================================
' CAMPOS DE INSTANCIA
' ============================================================
Private ReadOnly _http As HttpClient Private ReadOnly _http As HttpClient
Private ReadOnly _idAplicacion As Integer Private ReadOnly _idAplicacion As Integer
@@ -15,64 +35,132 @@ Public Class TsNotificacionesClient
_idAplicacion = idAplicacion _idAplicacion = idAplicacion
ServicePointManager.ServerCertificateValidationCallback = Function(s, c, ch, e) True ServicePointManager.ServerCertificateValidationCallback = Function(s, c, ch, e) True
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Or SecurityProtocolType.Tls11 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Or SecurityProtocolType.Tls11
_http = New HttpClient() With {.BaseAddress = New Uri(baseUrl)} _http = New HttpClient() With {.BaseAddress = New Uri(baseUrl)}
_http.DefaultRequestHeaders.Add("X-Api-Key", apiKey) _http.DefaultRequestHeaders.Add("X-Api-Key", apiKey)
End Sub End Sub
Public Shared Async Function RegistrarAsync(titulo As String, descripcion As String, TipoNotificacion As TipoNotificacionEnum, Optional Fichero As Byte() = Nothing) As Task ' ============================================================
' MÉTODO PRINCIPAL: REGISTRAR NOTIFICACIÓN
' ============================================================
Public Shared Async Function RegistrarAsync(titulo As String, descripcion As String, TipoNotificacion As TipoNotificacionEnum, Optional Fichero As Byte() = Nothing, Optional IncluirMensajeEnLogDelSistema As Boolean = True) As Task
Try Try
Dim logger = LogProvider.CreateLogger(Of TsNotificacionesClient)()
ServicePointManager.ServerCertificateValidationCallback = Function(s, c, ch, e) True ServicePointManager.ServerCertificateValidationCallback = Function(s, c, ch, e) True
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Or SecurityProtocolType.Tls11 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Or SecurityProtocolType.Tls11
'Dim baseUrl = ConfigurationManager.AppSettings("TsNotificaciones:ApiUrl") Dim config = New ConfigurationBuilder().
'Dim idAplicacion = Integer.Parse(ConfigurationManager.AppSettings("TsNotificaciones:IdAplicacion")) SetBasePath(Directory.GetCurrentDirectory()).
'Dim apiKey = ConfigurationManager.AppSettings("TsNotificaciones:ApiKey") AddJsonFile("appsettings.json", [optional]:=False).
'Dim http = New HttpClient() With {.BaseAddress = New Uri(baseUrl)} Build()
'Dim NombreServidor = ConfigurationManager.AppSettings("TsNotificaciones:ApiKey")
'If NombreServidor = "" Then NombreServidor = System.Environment.MachineName
Dim config = New ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", [optional]:=False).Build()
Dim apiUrl = If(config("TsNotificaciones:ApiUrl"), "http://localhost:7159") Dim apiUrl = If(config("TsNotificaciones:ApiUrl"), "http://localhost:7159")
Dim idAplicacion = Integer.Parse(If(config("TsNotificaciones:IdAplicacion"), "1")) Dim idAplicacion = Integer.Parse(If(config("TsNotificaciones:IdAplicacion"), "1"))
Dim Origen = If(config("TsNotificaciones:Origen"), "Tecnosis")
Dim Aplicacion = If(config("TsNotificaciones:Aplicacion"), idAplicacion.ToString)
Dim apiKey = If(config("TsNotificaciones:ApiKey"), String.Empty) Dim apiKey = If(config("TsNotificaciones:ApiKey"), String.Empty)
Dim nombreServidor = If(config("TsNotificaciones:NombreServidor"), Environment.MachineName) Dim nombreServidor = If(config("TsNotificaciones:NombreServidor"), Environment.MachineName)
Dim EsWindows = OperatingSystem.IsWindows()
If IncluirMensajeEnLogDelSistema Then
' ============================================================
' LOGGING MULTIPLATAFORMA
' ============================================================
If EsWindows Then
' --- WINDOWS: Event Viewer ---
If Not EventLog.SourceExists(Origen) Then
EventLog.CreateEventSource(Origen, Aplicacion)
End If
Dim ele As EventLogEntryType
Select Case TipoNotificacion
Case TipoNotificacionEnum.INFO
ele = EventLogEntryType.Information
Case TipoNotificacionEnum.ADVERTENCIA
ele = EventLogEntryType.Warning
Case TipoNotificacionEnum.ERROR, TipoNotificacionEnum.CRÍTICO
ele = EventLogEntryType.Error
End Select
EventLog.WriteEntry(Origen, $"{titulo} {descripcion}", ele)
Else
' --- LINUX: ILogger → journald ---
Select Case TipoNotificacion
Case TipoNotificacionEnum.INFO
logger.LogInformation($"{titulo} {descripcion}")
Case TipoNotificacionEnum.ADVERTENCIA
logger.LogWarning($"{titulo} {descripcion}")
Case TipoNotificacionEnum.ERROR, TipoNotificacionEnum.CRÍTICO
logger.LogError($"{titulo} {descripcion}")
End Select
End If
End If
' ============================================================
' LLAMADA A LA API
' ============================================================
Dim http = New HttpClient() With {.BaseAddress = New Uri(apiUrl)} Dim http = New HttpClient() With {.BaseAddress = New Uri(apiUrl)}
Dim Tipo = CInt(TipoNotificacion) Dim Tipo = CInt(TipoNotificacion)
Dim request = New HttpRequestMessage(HttpMethod.Post, "/api/alertas/registrar") Dim request = New HttpRequestMessage(HttpMethod.Post, "/api/alertas/registrar")
request.Headers.Add("X-Api-Key", apiKey) request.Headers.Add("X-Api-Key", apiKey)
Dim ipServidor As String = ObtenerIp() Dim ipServidor As String = ObtenerIp()
request.Content = JsonContent.Create(New With {idAplicacion, nombreServidor, ipServidor, titulo, descripcion, Tipo})
request.Content = JsonContent.Create(New With {
idAplicacion,
nombreServidor,
ipServidor,
titulo,
descripcion,
Tipo
})
Dim response = Await http.SendAsync(request) Dim response = Await http.SendAsync(request)
Dim body As System.Text.Json.JsonElement = Await response.Content.ReadFromJsonAsync(Of System.Text.Json.JsonElement)() Dim body As System.Text.Json.JsonElement = Await response.Content.ReadFromJsonAsync(Of System.Text.Json.JsonElement)()
Dim id = body.GetProperty("id").GetInt32() Dim id = body.GetProperty("id").GetInt32()
If Fichero IsNot Nothing Then If Fichero IsNot Nothing Then
Await SubirFichero(http, apiKey, id, Fichero) Await SubirFichero(http, apiKey, id, Fichero)
End If End If
Catch ex As Exception Catch ex As Exception
Throw New Exception(ex.Message, ex) Throw New Exception(ex.Message, ex)
End Try End Try
End Function End Function
' ============================================================
' SUBIR FICHERO
' ============================================================
Private Shared Async Function SubirFichero(ByVal http As HttpClient, ByVal apiKey As String, ByVal alertaId As Integer, ByVal datos As Byte()) As Task Private Shared Async Function SubirFichero(ByVal http As HttpClient, ByVal apiKey As String, ByVal alertaId As Integer, ByVal datos As Byte()) As Task
Try Try
Dim fileContent = New ByteArrayContent(datos) Dim fileContent = New ByteArrayContent(datos)
fileContent.Headers.ContentType = New MediaTypeHeaderValue("image/png") fileContent.Headers.ContentType = New MediaTypeHeaderValue("image/png")
Dim multipart = New MultipartFormDataContent() Dim multipart = New MultipartFormDataContent()
multipart.Add(fileContent, "archivo", "Imagen.png") multipart.Add(fileContent, "archivo", "Imagen.png")
Dim request = New HttpRequestMessage(HttpMethod.Post, $"/api/alertas/{alertaId}/archivo") Dim request = New HttpRequestMessage(HttpMethod.Post, $"/api/alertas/{alertaId}/archivo")
request.Headers.Add("X-Api-Key", apiKey) request.Headers.Add("X-Api-Key", apiKey)
request.Content = multipart request.Content = multipart
Dim response = Await http.SendAsync(request) Dim response = Await http.SendAsync(request)
Dim ok As Boolean = response.IsSuccessStatusCode If Not response.IsSuccessStatusCode Then
If Not ok Then Throw New Exception($"Subida fallida ({response.StatusCode}): {Await response.Content.ReadAsStringAsync()}") Throw New Exception($"Subida fallida ({response.StatusCode}): {Await response.Content.ReadAsStringAsync()}")
End If
Catch httpEx As Exception Catch httpEx As Exception
Throw New Exception Throw New Exception(httpEx.Message, httpEx)
End Try End Try
End Function End Function
' ============================================================
' OBTENER IP
' ============================================================
Private Shared Function ObtenerIp() As String Private Shared Function ObtenerIp() As String
For Each addr In Dns.GetHostAddresses(Dns.GetHostName()) For Each addr In Dns.GetHostAddresses(Dns.GetHostName())
If addr.AddressFamily = Sockets.AddressFamily.InterNetwork Then Return addr.ToString() If addr.AddressFamily = Sockets.AddressFamily.InterNetwork Then Return addr.ToString()
@@ -80,13 +168,14 @@ Public Class TsNotificacionesClient
Return "127.0.0.1" Return "127.0.0.1"
End Function End Function
'Private Shared Function EscaparJson(s As String) As String ' ============================================================
' Return s.Replace("\", "\\").Replace("""", "\""").Replace(vbCr, "\r").Replace(vbLf, "\n") ' ENUMERACIÓN
'End Function ' ============================================================
Public Enum TipoNotificacionEnum Public Enum TipoNotificacionEnum
INFO = 0 INFO = 0
ADVERTENCIA = 1 ADVERTENCIA = 1
[ERROR] = 2 [ERROR] = 2
CRÍTICO = 3 CRÍTICO = 3
End Enum End Enum
End Class End Class

View File

@@ -16,11 +16,12 @@
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<PackageId>tsUtilidades</PackageId> <PackageId>tsUtilidades</PackageId>
<PackageTags>net8.0, libreria</PackageTags> <PackageTags>net8.0, libreria</PackageTags>
<Version>1.1.10</Version> <Version>1.1.11</Version>
<Authors>Manuel</Authors> <Authors>Manuel</Authors>
<Company>Tecnosis S.A</Company> <Company>Tecnosis S.A</Company>
<Description>Utilidades Varias</Description> <Description>Utilidades Varias</Description>
<PackageReleaseNotes> <PackageReleaseNotes>
- 2026-04-28 1.1.11 Se añade log del sistema a tsNotificacionesClient
- 2026-04-10 1.1.10 Se corrige tsNotificacionesClient - 2026-04-10 1.1.10 Se corrige tsNotificacionesClient
- 2026-04-10 1.1.9 Se corrige tsNotificacionesClient - 2026-04-10 1.1.9 Se corrige tsNotificacionesClient
- 2026-04-09 1.1.8 Se añade la clase tsNotificacionesClient - 2026-04-09 1.1.8 Se añade la clase tsNotificacionesClient