Jump to content

SyslogSend UDF - send messages to a syslog server


Irios
 Share

Recommended Posts

Note: my first UDF.

This allows sending (BSD) messages to a syslog server using UDP. It has been tested with SnmpSoft Syslog Watcher, Synology DSM 4.2 and DSM 6.0, Kiwi Syslog Server.

Uses the BSD syslog protocol (https://tools.ietf.org/html/rfc3164), except for Facility and Severity levels, which incorporates the extended (newer) values as well. To the best of my knowledge, this is how most basic syslog senders do it today anyway.

Target IP, Facility, Severity level, Tag, Hostname, Port can be specified.

Also includes a ping feature to give an error if server doesn't respond.

Feedback appreciated.

#include-once

Global $__SyslogSendPing ; this allows global access to the ping result (in ms)
Global $__SyslogSendPacket ; this allows global access to the entire syslog packet: PRI, HEADER and MSG.

; #FUNCTION# ====================================================================================================================
; Name ..........: SyslogSend v1.0.3
; Modified ......: 2018.10.09
; Changelog......: v1.0.2 fixed $MDAY formatting, leading zero would not be correctly replaced by a space
;                  v1.0.3 added debug console output when packet is sent. Set global variable  $_D=True  to show debug output.
; Description ...: Sends syslog messages to a syslog server using UDP
; Syntax ........: SyslogSend($_Message, $_Target, $_Port, $_Facility, $_Severity, $_Tag, $_HostName)
; Parameters ....: $_Message            - Text message to send. https://tools.ietf.org/html/draft-ietf-syslog-protocol-23#section-6.4
;                  $_Target             - [optional] Target IP or host (IPv4 address or hostname). Default is "127.0.0.1".
;                  $_Facility           - [optional] Facility value (integer 0..23). Default is 1. https://tools.ietf.org/html/draft-ietf-syslog-protocol-23#section-6.2.1
;                  $_Severity           - [optional] Severity level (integer 0..7). Default is 7. https://tools.ietf.org/html/draft-ietf-syslog-protocol-23#section-6.2.1
;                  $_Tag                - [optional] Name of program or process (a-zA-Z0-9). https://tools.ietf.org/html/rfc3164#section-4.1.3
;                  $_HostName           - [optional] Originator hostname. Default is @ComputerName. https://tools.ietf.org/html/rfc3164#section-4.1.2
;                  $_Port               - [optional] UDP port number (integer 0..65535). Default is 514.
;                  $_Ping               - [optional] Ping the host before sending, with value as timeout. Function will exit and return an
;                                         error message if host did not respond. Default is 0 (no ping).
; Return values .: 0 = Success
;                  Non-zero = error text message
; Author ........: Irios
; Remarks .......: Uses UDP only, and sticks to the BSD syslog protocol (https://tools.ietf.org/html/rfc3164), except for Facility
;                  and Severity levels, which incorporates the extended (newer) values as well. To the best of my knowledge, this
;                  is how most basic syslog senders do it today anyway. The syslog protocol does not provide acknowledgement of message
;                  delivery, the ping feature is for convenience only. Most syslog servers will use the first word in the MSG field as
;                  TAG if you do not specify a tag yourself. This is by design, and not a bug.
; Example .......: SyslogSend("A test message", "192.168.0.1", 514, 3, 5, "SyslogSend", "fooServer", 1000)
;                  This would send the text string "<29> Oct  1 00:36:23 fooServer SyslogSend: A test message" to host 192.168.0.1:514 (including a ping, 1000ms timeout).
;
; ===============================================================================================================================
Func SyslogSend($_Message, $_Target = "127.0.0.1", $_Facility = 1, $_Severity = 7, $_Tag = "", $_HostName = @ComputerName, $_Port = 514, $_Ping = 0)

    Local $_UDPStartup = False
    If (StringStripWS($_Message, 8) = "") Then Return "Error. Nothing to send (no message content)."

    If ($_Target = "") Or (Int($_Port) < 0) Or (Int($_Port) > 65535) Or (Int($_Facility) < 0) Or (Int($_Facility) > 23) Or (Int($_Severity) < 0) Or (Int($_Severity) > 7) Then Return "Argument(s) error." ; quick check to make sure most of the parameters have valid values

    ; Strip accidental spaces from target IP, HOSTNAME, and TAG. Adding a colon and space to the TAG field (https://tools.ietf.org/html/rfc3164#section-4.1.3)
    $_Target = StringStripWS($_Target, 8)
    $_HostName = StringStripWS($_HostName, 8)
    If ($_Tag <> "") Then $_Tag = StringStripWS($_Tag, 8) & ": "

    ; Ping the target host, and return an error if not responding
    If (Int($_Ping) <> 0) Then
        $__SyslogSendPing = Ping($_Target, $_Ping)
        Switch @error
            Case 1
                $__SyslogSendPing = ""
                Return "Ping error. Host is offline."
            Case 2
                $__SyslogSendPing = ""
                Return "Ping error. Host is unreachable."
            Case 3
                $__SyslogSendPing = ""
                Return "Ping error. Bad destination."
            Case 4
                $__SyslogSendPing = ""
                Return "Ping error. Other error."
        EndSwitch
    EndIf


    ; Format the TIMESTAMP field. Month number converted to Mmm format (https://tools.ietf.org/html/rfc3164#section-4.1.2). Replace leading zero in day with a space.
    Switch @MON
        Case 1
            $MON = "Jan"
        Case 2
            $MON = "Feb"
        Case 3
            $MON = "Mar"
        Case 4
            $MON = "Apr"
        Case 5
            $MON = "May"
        Case 6
            $MON = "Jun"
        Case 7
            $MON = "Jul"
        Case 8
            $MON = "Aug"
        Case 9
            $MON = "Sep"
        Case 10
            $MON = "Oct"
        Case 11
            $MON = "Nov"
        Case 12
            $MON = "Dec"
    EndSwitch
    $MDAY = " " & @MDAY                             ; we add a leading space for easier processing/formatting...
    $MDAY = StringReplace($MDAY, " 0", "  ", 1)     ; ...here we make sure the MDAY variable always has the same length (incl. a trailing space). Value such as "03" is illegal, and must be formatted as " 3".
    Local $_TimeStampNow = $MON & $MDAY & " " & @HOUR & ":" & @MIN & ":" & @SEC ; the complete TIMESTAMP field (https://tools.ietf.org/html/rfc3339)

    Local $_Prival = Int(($_Facility * 8) + $_Severity) ; generating the <PRIVAL> for the PRI field. Multiply the Facility number by 8 and add the numerical value of the Severity (https://tools.ietf.org/html/rfc5424#section-6.2.1)

    $__SyslogSendPacket = "<" & $_Prival & "> " & $_TimeStampNow & " " & $_HostName & " " & $_Tag & $_Message   ; the complete syslog packet (https://tools.ietf.org/html/rfc3164#section-4.1.3)
    If (Eval("_D")=True) Then ConsoleWrite('DEBUG SyslogSend(): "'& $__SyslogSendPacket & '"' & @CRLF)          ; debug output, uses $_D as trigger

    UDPStartup() ; starting the UDP service
    If @error Then
        Return "Could not start UDP service. Error " & @error
    Else
        $_UDPStartup = True
    EndIf


    Local $_Socket = UDPOpen($_Target, $_Port) ; the socket for the UDP connection
    If @error Then
        If $_UDPStartup Then UDPShutdown()
        Return "Could not connect. Error " & @error
    EndIf

    UDPSend($_Socket, $__SyslogSendPacket) ; sending the packet
    If @error Then
        If $_UDPStartup Then UDPShutdown()
        Return "Could not send the data. Error " & @error
    EndIf

    UDPCloseSocket($_Socket) ; closing the socket
    If @error Then
        If $_UDPStartup Then UDPShutdown()
        Return "Could not close socket. Error " & @error
    EndIf

    If $_UDPStartup Then UDPShutdown() ; Close the UDP service.

EndFunc   ;==>SyslogSend

Changelog:

v1.0.1  added #include-once
v1.0.2  fixed $MDAY formatting, leading zero would not be correctly replaced by a space
v1.0.3  added $_D option for debug output, see source comment for usage

 

 

 

 

SyslogSend_udf.au3

Edited by Irios
v1.0.3

863nP4W.png discord.me/autoit  (unofficial)

Link to comment
Share on other sites

Thanks for sharing.
Here is my little modyfication:

#include-once
#include <StringConstants.au3>
Global $__g_iSyslogSendPing ; this allows global access to the ping result (in ms)
Global $__g_sSyslogSendPacket ; this allows global access to the entire syslog packet: PRI, HEADER and MSG.

; #FUNCTION# ====================================================================================================================
; Name ..........: SyslogSend v1.0
; Description ...: Sends syslog messages to a syslog server using UDP
; Syntax ........: SyslogSend($_Message, $_Target, $_Port, $_Facility, $_Severity, $_Tag, $_HostName)
; Parameters ....: $_Message            - Text message to send. https://tools.ietf.org/html/draft-ietf-syslog-protocol-23#section-6.4
;                  $_Target             - [optional] Target IP or host (IPv4 address or hostname). Default is "127.0.0.1".
;                  $_Facility           - [optional] Facility value (integer 0..23). Default is 1. https://tools.ietf.org/html/draft-ietf-syslog-protocol-23#section-6.2.1
;                  $_Severity           - [optional] Severity level (integer 0..7). Default is 7. https://tools.ietf.org/html/draft-ietf-syslog-protocol-23#section-6.2.1
;                  $_Tag                - [optional] Name of program or process (a-zA-Z0-9). https://tools.ietf.org/html/rfc3164#section-4.1.3
;                  $_HostName           - [optional] Originator hostname. Default is @ComputerName. https://tools.ietf.org/html/rfc3164#section-4.1.2
;                  $_Port               - [optional] UDP port number (integer 0..65535). Default is 514.
;                  $_Ping               - [optional] Ping the host before sending, with value as timeout. Function will exit and return an
;                                         error message if host did not respond. Default is 0 (no ping).
; Return values .: 0 = Success
;                  Non-zero = error text message
; Author ........: Irios
; Modified ......: 2016.10.01
; Remarks .......: Uses UDP only, and sticks to the BSD syslog protocol (https://tools.ietf.org/html/rfc3164), except for Facility
;                  and Severity levels, which incorporates the extended (newer) values as well. To the best of my knowledge, this
;                  is how most basic syslog senders do it today anyway. The syslog protocol does not provide acknowledgement of message
;                  delivery, the ping feature is for convenience only. Most syslog servers will use the first word in the MSG field as
;                  TAG if you do not specify a tag yourself. This is by design, and not a bug.
; Example .......: SyslogSend("A test message", "192.168.0.1", 514, 3, 5, "SyslogSend", "fooServer", 1000)
;                  This would send the text string "<29> Oct  1 00:36:23 fooServer SyslogSend: A test message" to host 192.168.0.1:514 (including a ping, 1000ms timeout).
; ===============================================================================================================================
Func SyslogSend($_Message, $_Target = "127.0.0.1", $_Facility = 1, $_Severity = 7, $_Tag = "", $_HostName = @ComputerName, $_Port = 514, $_Ping = 0)

    If (StringStripWS($_Message, $STR_STRIPALL) = "") Then Return SetError(1, 0, "Error. Nothing to send (no message content).")

    If _
            ($_Target = "") Or (Int($_Port) < 0) _
            Or (Int($_Port) > 65535) Or (Int($_Facility) < 0) _
            Or (Int($_Facility) > 23) Or (Int($_Severity) < 0) _
            Or (Int($_Severity) > 7) _
            Then Return SetError(1, 0, "Argument(s) error.") ; quick check to make sure most of the parameters have valid values

    ; Strip accidental spaces from target IP, HOSTNAME, and TAG. Adding a colon and space to the TAG field (https://tools.ietf.org/html/rfc3164#section-4.1.3)
    $_Target = StringStripWS($_Target, $STR_STRIPALL)
    $_HostName = StringStripWS($_HostName, $STR_STRIPALL)
    If ($_Tag <> "") Then $_Tag = StringStripWS($_Tag, $STR_STRIPALL) & ": "

    ; Ping the target host, and return an error if not responding
    If (Int($_Ping) <> 0) Then
        $__g_iSyslogSendPing = Ping($_Target, $_Ping)
        Switch @error
            Case 1
                $__g_iSyslogSendPing = -1
                Return SetError(3, @error, "Ping error. Host is offline.")
            Case 2
                $__g_iSyslogSendPing = -1
                Return SetError(3, @error, "Ping error. Host is unreachable.")
            Case 3
                $__g_iSyslogSendPing = -1
                Return SetError(3, @error, "Ping error. Bad destination.")
            Case 4
                $__g_iSyslogSendPing = -1
                Return SetError(3, @error, "Ping error. Other error.")
        EndSwitch
    EndIf

    ; Format the TIMESTAMP field. Month number converted to Mmm format (https://tools.ietf.org/html/rfc3164#section-4.1.2). Replace leading zero in day with a space.
    Switch @MON
        Case 1
            $MON = "Jan"
        Case 2
            $MON = "Feb"
        Case 3
            $MON = "Mar"
        Case 4
            $MON = "Apr"
        Case 5
            $MON = "May"
        Case 6
            $MON = "Jun"
        Case 7
            $MON = "Jul"
        Case 8
            $MON = "Aug"
        Case 9
            $MON = "Sep"
        Case 10
            $MON = "Oct"
        Case 11
            $MON = "Nov"
        Case 12
            $MON = "Dec"
    EndSwitch
    $MDAY = StringReplace(" " & @MDAY, " 0", " ", 1)

    ; the complete TIMESTAMP field (https://tools.ietf.org/html/rfc3339)
    Local $_TimeStampNow = $MON & " " & $MDAY & " " & @HOUR & ":" & @MIN & ":" & @SEC

    ; generating the <PRIVAL> for the PRI field. Multiply the Facility number by 8 and add the numerical value of the Severity (https://tools.ietf.org/html/rfc5424#section-6.2.1)
    Local $_Prival = Int(($_Facility * 8) + $_Severity)

    ; the complete syslog packet (https://tools.ietf.org/html/rfc3164#section-4.1.3)
    $__g_sSyslogSendPacket = "<" & $_Prival & "> " & $_TimeStampNow & " " & $_HostName & " " & $_Tag & $_Message

    ; starting the UDP service
    UDPStartup()
    If @error Then Return SetError(4, 0, "Could not start UDP service. Error " & @error)

    ; the socket for the UDP connection
    Local $_Socket = UDPOpen($_Target, $_Port)
    If @error Then Return SetError(5, __SysLog_UDPShutDown(), "Could not connect. Error " & @error)

    ; sending the packet
    UDPSend($_Socket, $__g_sSyslogSendPacket)
    If @error Then Return SetError(6, __SysLog_UDPShutDown(), "Could not send the data. Error " & @error)

    ; closing the socket
    UDPCloseSocket($_Socket)
    If @error Then Return SetError(7, __SysLog_UDPShutDown(), "Could not close socket. Error " & @error)

    ; Close the UDP service.
    UDPShutdown()

EndFunc   ;==>SyslogSend

Func __SysLog_UDPShutDown($iError = @error, $iExtended = @extended)
    UDPShutdown()
    Return SetError($iError, $iExtended, @error)
EndFunc   ;==>__SysLog_UDPShutDown

 

Edited by mLipok
script edited.

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

 

@mLipok

Ah, yes I forgot about the #include-once

Besides reformatting some of the longer lines (and StringConstants.au3), did you do any other changes/optimizations? At first glance I cannot see any ... hmmm. A "changelog" would be nice, you know ;)

(FYI I prefer not to #include more files in my UDFs as long as its practical, so they don't depend on external files. I hate to download or add an UDF, just to discover it requires a file or two to run.)

 

EDIT: lol nevermind, I am blind. Yeah, making a separate function for the UPSShutdown() is a nice edit

Edited by Irios

863nP4W.png discord.me/autoit  (unofficial)

Link to comment
Share on other sites

Quote

- Global Variable Renaming
- $_UDPStartup - removed was not needed
- If .. or ... or .... or - added continuation line for clarity of code
- StringStripWS - magic number fixed
- better error checking - used Return SetError(.....
- comments relocation - for clarity of code
- new function: __SysLog_UDPShutDown() - to make script smaller

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

#include-once
#include <StringConstants.au3>
Global $__g_iSyslogSendPing ; this allows global access to the ping result (in ms)
Global $__g_sSyslogSendPacket ; this allows global access to the entire syslog packet: PRI, HEADER and MSG.
Global $__g_aSyslog_Months[13] = [0, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

#cs
    CHANGELOG
    2016-10-01
    - First release - Irios

    2016-10-01
    - Changed: Global Variable Renaming - mLipok
    - Removed: $_UDPStartup - removed was not needed - mLipok
    - Changed: If .. or ... or .... or - added continuation line for clarity of code - mLipok
    - Changed: StringStripWS - magic number fixed - mLipok
    - Changed: better error checking - used Return SetError(..... - mLipok
    - Changed: comments relocation - for clarity of code - mLipok
    - Added: function: __SysLog_UDPShutDown() - to make function smaller (easier to maintain) - mLipok

    2016-10-02
    - Changed: $__g_iSyslogSendPing - 0 mean error, so $__SyslogSendPing = "" was not needed - mLipok
    - Changed: $__g_iSyslogSendPing = -1 - in case when PING was not used  - mLipok
    - Added: $__g_aSyslog_Months instead Switch @MON - mLipok
#ce

; #FUNCTION# ====================================================================================================================
; Name ..........: SyslogSend v1.0
; Description ...: Sends syslog messages to a syslog server using UDP
; Syntax ........: SyslogSend($_Message, $_Target, $_Port, $_Facility, $_Severity, $_Tag, $_HostName)
; Parameters ....: $_Message            - Text message to send. https://tools.ietf.org/html/draft-ietf-syslog-protocol-23#section-6.4
;                  $_Target             - [optional] Target IP or host (IPv4 address or hostname). Default is "127.0.0.1".
;                  $_Facility           - [optional] Facility value (integer 0..23). Default is 1. https://tools.ietf.org/html/draft-ietf-syslog-protocol-23#section-6.2.1
;                  $_Severity           - [optional] Severity level (integer 0..7). Default is 7. https://tools.ietf.org/html/draft-ietf-syslog-protocol-23#section-6.2.1
;                  $_Tag                - [optional] Name of program or process (a-zA-Z0-9). https://tools.ietf.org/html/rfc3164#section-4.1.3
;                  $_HostName           - [optional] Originator hostname. Default is @ComputerName. https://tools.ietf.org/html/rfc3164#section-4.1.2
;                  $_Port               - [optional] UDP port number (integer 0..65535). Default is 514.
;                  $_Ping               - [optional] Ping the host before sending, with value as timeout. Function will exit and return an
;                                         error message if host did not respond. Default is 0 (no ping).
; Return values .: 0 = Success
;                  Non-zero = error text message
; Author ........: Irios
; Modified ......: mLipok
; Remarks .......: Uses UDP only, and sticks to the BSD syslog protocol (https://tools.ietf.org/html/rfc3164), except for Facility
;                  and Severity levels, which incorporates the extended (newer) values as well. To the best of my knowledge, this
;                  is how most basic syslog senders do it today anyway. The syslog protocol does not provide acknowledgement of message
;                  delivery, the ping feature is for convenience only. Most syslog servers will use the first word in the MSG field as
;                  TAG if you do not specify a tag yourself. This is by design, and not a bug.
; Example .......: SyslogSend("A test message", "192.168.0.1", 514, 3, 5, "SyslogSend", "fooServer", 1000)
;                  This would send the text string "<29> Oct  1 00:36:23 fooServer SyslogSend: A test message" to host 192.168.0.1:514 (including a ping, 1000ms timeout).
; ===============================================================================================================================
Func SyslogSend($_Message, $_Target = "127.0.0.1", $_Facility = 1, $_Severity = 7, $_Tag = "", $_HostName = @ComputerName, $_Port = 514, $_Ping = 0)

    If (StringStripWS($_Message, $STR_STRIPALL) = "") Then Return SetError(1, 0, "Error. Nothing to send (no message content).")

    If _
            ($_Target = "") Or (Int($_Port) < 0) _
            Or (Int($_Port) > 65535) Or (Int($_Facility) < 0) _
            Or (Int($_Facility) > 23) Or (Int($_Severity) < 0) _
            Or (Int($_Severity) > 7) _
            Then Return SetError(1, 0, "Argument(s) error.") ; quick check to make sure most of the parameters have valid values

    ; Strip accidental spaces from target IP, HOSTNAME, and TAG. Adding a colon and space to the TAG field (https://tools.ietf.org/html/rfc3164#section-4.1.3)
    $_Target = StringStripWS($_Target, $STR_STRIPALL)
    $_HostName = StringStripWS($_HostName, $STR_STRIPALL)
    If ($_Tag <> "") Then $_Tag = StringStripWS($_Tag, $STR_STRIPALL) & ": "

    $__g_iSyslogSendPing - 1 ; -1 mean PING was not used
    ; Ping the target host, and return an error if not responding
    If (Int($_Ping) <> 0) Then
        $__g_iSyslogSendPing = Ping($_Target, $_Ping)
        Switch @error
            Case 1
                Return SetError(3, @error, "Ping error. Host is offline.")
            Case 2
                Return SetError(3, @error, "Ping error. Host is unreachable.")
            Case 3
                Return SetError(3, @error, "Ping error. Bad destination.")
            Case 4
                Return SetError(3, @error, "Ping error. Other error.")
        EndSwitch
    EndIf

    ; Format the TIMESTAMP field. Month number converted to Mmm format (https://tools.ietf.org/html/rfc3164#section-4.1.2). Replace leading zero in day with a space.
    $MDAY = StringReplace(" " & @MDAY, " 0", " ", 1)

    ; the complete TIMESTAMP field (https://tools.ietf.org/html/rfc3339)
    Local $_TimeStampNow = $__g_aSyslog_Months[@MON] & " " & $MDAY & " " & @HOUR & ":" & @MIN & ":" & @SEC

    ; generating the <PRIVAL> for the PRI field. Multiply the Facility number by 8 and add the numerical value of the Severity (https://tools.ietf.org/html/rfc5424#section-6.2.1)
    Local $_Prival = Int(($_Facility * 8) + $_Severity)

    ; the complete syslog packet (https://tools.ietf.org/html/rfc3164#section-4.1.3)
    $__g_sSyslogSendPacket = "<" & $_Prival & "> " & $_TimeStampNow & " " & $_HostName & " " & $_Tag & $_Message

    ; starting the UDP service
    UDPStartup()
    If @error Then Return SetError(4, 0, "Could not start UDP service. Error " & @error)

    ; the socket for the UDP connection
    Local $_Socket = UDPOpen($_Target, $_Port)
    If @error Then Return SetError(5, __SysLog_UDPShutDown(), "Could not connect. Error " & @error)

    ; sending the packet
    UDPSend($_Socket, $__g_sSyslogSendPacket)
    If @error Then Return SetError(6, __SysLog_UDPShutDown(), "Could not send the data. Error " & @error)

    ; closing the socket
    UDPCloseSocket($_Socket)
    If @error Then Return SetError(7, __SysLog_UDPShutDown(), "Could not close socket. Error " & @error)

    ; Close the UDP service.
    UDPShutdown()

EndFunc   ;==>SyslogSend

Func __SysLog_UDPShutDown($iError = @error, $iExtended = @extended)
    UDPShutdown()
    Return SetError($iError, $iExtended, @error)
EndFunc   ;==>__SysLog_UDPShutDown

Such a small improvement ;)

ps.
I just had to focus thoughts on such a small project, to be able to return to work on other large projects, a little interlude - freshener mind.

Do not be mad at me, just analyze the changes.

Edited by mLipok

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...