Write to Windows event log: Difference between revisions
m
→{{header|Wren}}: Minor tidy
(→{{header|Tcl}}: + SML) |
m (→{{header|Wren}}: Minor tidy) |
||
(9 intermediate revisions by 9 users not shown) | |||
Line 4:
Write script status to the Windows Event Log
<br><br>
=={{header|11l}}==
{{trans|C}}
<syntaxhighlight lang="11l">:start:
I :argv.len != 5
print(‘Usage : #. < Followed by level, id, source string and description>’.format(:argv[0]))
E
os:(‘EventCreate /t #. /id #. /l APPLICATION /so #. /d "#."’.format(:argv[1], :argv[2], :argv[3], :argv[4]))</syntaxhighlight>
=={{header|AutoHotkey}}==
<
h := RegisterForEvents("AutoHotkey")
SendWinLogEvent(h, "Test Message")
Line 40 ⟶ 49:
SendWinLogEvent(hSource, String="", evType=0x0004, evId=0x03EA, evCat=0, pData=0) {
Ptr := A_PtrSize ? "Ptr" : "UInt"
LPCtSTRs := A_PtrSize ? "Ptr*" : "UInt"
StringPut := A_IsUnicode ? "StrPut" : "StrPut2"
; Reserve and initialise space for the event message.
VarSetCapacity(eventMessage, StrLen(String), 0)
%StringPut%(String, &eventMessage, A_IsUnicode ? "UTF-16" : "")
r := DllCall("Advapi32.dll\ReportEvent" (A_IsUnicode ? "W" : "A")
, UInt, hSource ; handle
Line 51 ⟶ 60:
, UShort, evCat ; WORD, category
, UInt, evId ; DWORD, event ID, 0x03EA
, Ptr, 0
, UShort, 1
, UInt, VarSetCapacity(pData)
,
, Ptr, (VarSetCapacity(pData)) ? &pData : 0 ) ; ptr to a buffer of binary data
Line 195 ⟶ 204:
; Return the number of characters copied.
return char_count
}</
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f WRITE_TO_WINDOWS_EVENT_LOG.AWK
BEGIN {
Line 217 ⟶ 226:
}
function error(message) { printf("error: %s\n",message) ; errors++ }
</syntaxhighlight>
{{out}}
<pre>
Line 225 ⟶ 234:
=={{header|Batch File}}==
The "EventCreate" command does the task.
<
EventCreate /t ERROR /id 123 /l SYSTEM /so "A Batch File" /d "This is found in system log."
EventCreate /t WARNING /id 456 /l APPLICATION /so BlaBla /d "This is found in apps log"</
{{Out}}
<pre>>EventLog.BAT
Line 237 ⟶ 246:
></pre>
If you do not want the command to display its result or errors...
<
EventCreate /t ERROR /id 123 /l SYSTEM /so "A Batch File" /d "This is found in system log."
EventCreate /t WARNING /id 456 /l APPLICATION /so BlaBla /d "This is found in apps log"
::That "
'''NOTE:''' This will (...or might) not work if you do not have administrator privileges.
Line 247 ⟶ 256:
{{works with|BBC BASIC for Windows}}
Writes to the Application Log:
<
PROC_cominitlcid(1033)
Line 254 ⟶ 263:
PROC_releaseobject(WshShell%)
PROC_comexit</
=={{header|C}}==
The following is a wrapper on the EventCreate utility provided in Windows. Note that to use this wrapper, the code must be executed from a console/IDE running as Administrator. The utility itself does extensive error-checking and validation, so apart from the check that 5 arguments have been supplied, no other validations or checks are performed.
<syntaxhighlight lang="c">
#include<stdlib.h>
#include<stdio.h>
Line 275 ⟶ 284:
return 0;
}
</syntaxhighlight>
Invocation and output on console :
<pre>
Line 286 ⟶ 295:
=={{header|C sharp}}==
In Windows Vista and later or Windows Server 2003, you must have administrative privileges to execute this code.
<
namespace RC
Line 305 ⟶ 314:
}
}
}</
=={{header|C++}}==
{{trans|C}}
<
#include <sstream>
Line 329 ⟶ 338:
return 0;
}</
=={{header|Clojure}}==
<
(sh "eventcreate" "/T" "INFORMATION" "/ID" "123" "/D" "Rosetta Code example")</
=={{header|D}}==
{{trans|Kotlin}}
<
import std.stdio;
Line 348 ⟶ 357:
writeln("Failed to execute command, status=", cmd.status);
}
}</
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 376 ⟶ 385:
begin
WriteLog('Message to log.');
end.</
=={{header|F_Sharp|F#}}==
<p>Bare bone writing to the Application Eventlog giving no event-ID and using the default event type (information.)</p>
<
log.Source <- "Sample Application"
log.WriteEntry("Entered something in the Application Eventlog!")</
=={{header|Go}}==
This works on Windows 10 with administrative privileges.
<
import (
Line 402 ⟶ 411:
fmt.Println(err)
}
}</
=={{header|Java}}==
<
import java.io.IOException;
import java.io.InputStream;
Line 433 ⟶ 442:
}
}
}</
=={{header|Julia}}==
Run as an administrator.
<
cmd = "eventcreate /T INFORMATION /ID 123 /D \"Rosetta Code Write to Windows event log task example\""
Base.run(`$cmd`)
</syntaxhighlight>
=={{header|Kotlin}}==
The following works on Windows 10 with administrative privileges:
<
fun main(args: Array<String>) {
Line 455 ⟶ 464:
Runtime.getRuntime().exec(command)
}</
=={{header|Lingo}}==
{{libheader|Shell xtra}}
<
props = [:]
props["operation"] = "runas"
props["parameters"] = "/t INFORMATION /id 123 /l APPLICATION /so Lingo /d ""E&"Rosetta Code Example""E
shell.shell_exec("EventCreate", props)</
=={{header|Perl}}==
Line 469 ⟶ 478:
The Win32::EventLog module has the Report method to write in the EventLog
<
use strict;
use warnings;
Line 486 ⟶ 495:
};
$handle->Report($event);
</syntaxhighlight>
=={{header|Phix}}==
The first two lines are of course entirely optional, but could help prevent someone/a newbie from wasting their time trying to achieve the impossible.
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #004600;">WINDOWS</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (as in this will not work on Linux or p2js, duh)</span>
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (as above, also prevent pointless attempts to transpile)</span>
<span style="color: #7060A8;">system</span><span style="color: #0000FF;">(</span><span style="color: #008000;">`eventcreate /T INFORMATION /ID 123 /D "Rosetta Code Write to Windows event log task example"`</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}} (when running as administrator)
<pre>
Line 497 ⟶ 511:
=={{header|PicoLisp}}==
PicoLisp doesn't run on Windows. In case of Linux, the equivalent of the event log is the syslog. It can be written with '[http://software-lab.de/doc/refN.html#native native]' C functions, or simply with the 'logger' utility:
<
-> T
: (call 'logger "This" 'is "another" 'test)
-> T</
=={{header|PowerShell}}==
<
$EventLog=new-object System.Diagnostics.EventLog("Application")
#Declare Event Source; must be 'registered' with Windows
Line 516 ⟶ 530:
# Write the event in the format "Event test",EventType,EventID
$EventLog.WriteEntry("My Test Event",$infoevent,70)</
''Note1:'' Thanks to PoSH Fan for posting information that got me started on this at [http://winpowershell.blogspot.com/2006/07/writing-windows-events-using.html Windows PowerShell Blog]
<br>
Line 522 ⟶ 536:
===Source and event log existing===
<
$MessageFreeLula = 'Global unions and union leaders from more than 50 countries came together ' +
'in Geneva today to stand in solidarity with former Brazilian President Lula, calling for ' +
Line 528 ⟶ 542:
Write-EventLog -LogName 'System' -Source 'Eventlog' -Message $MessageFreeLula -EventId 13 -EntryType 'Information'
'SUCCESS: The Lula Livre message (#FreeLula) has been recorded in the system log event.'
</syntaxhighlight>
{{out|output}}
<pre>
Line 534 ⟶ 548:
</pre>
===New event log===
<
$MessageFreeLula = 'Global unions and union leaders from more than 50 countries came together ' +
'in Geneva today to stand in solidarity with former Brazilian President Lula, calling for ' +
Line 542 ⟶ 556:
Write-EventLog -LogName 'Free Lula!' -Source '#FreeLula' -Message $MessageFreeLula -EventId 13 -EntryType 'Information'
'SUCCESS: The Lula Livre message (#FreeLula) has been recorded in the "Free Lula!" log event.'
</syntaxhighlight>
{{out|output}}
<pre>
Line 549 ⟶ 563:
=={{header|PureBasic}}==
<
Protected wNumStrings.w, lpString=@EventMessage$, lReturnX, CMessageTyp, lparray
Line 562 ⟶ 576:
ProcedureReturn Result
EndProcedure</
=={{header|Python}}==
Line 568 ⟶ 582:
{{libheader|PyWin32}}
<
import win32con
import win32evtlog
Line 586 ⟶ 600:
win32evtlogutil.ReportEvent(applicationName, eventID, eventCategory=category,
eventType=myType, strings=descr, data=data, sid=my_sid)</
=={{header|Racket}}==
Racket's logging facility creates windows events when running on Windows.
<syntaxhighlight lang="racket">
#lang racket
(log-warning "Warning: nothing went wrong.")
</syntaxhighlight>
=={{header|Raku}}==
Line 603 ⟶ 617:
(Same caveats as the others, needs to be run as administrator or with elevated privileges under Windows.)
<syntaxhighlight lang="raku"
when .is-win {
my $cmd = "eventcreate /T INFORMATION /ID 123 /D \"Bla de bla bla bla\"";
Line 613 ⟶ 627:
$logger.info("[$*PROGRAM-NAME pid=$*PID user=$*USER] Just thought you might like to know.");
}
}</
=={{header|REXX}}==
Line 619 ⟶ 633:
===annotated===
<
eCMD = 'EVENTCREATE' /*name of the command that'll be used. */
Line 631 ⟶ 645:
eCMD '/T' type "/ID" id '/L' logName "/SO" source '/D' desc
/*stick a fork in it, we're all done. */</
{{out|output}}
<pre>
Line 638 ⟶ 652:
===bare bones===
<
/* [↓] cmd options have extra spacing.*/
Line 644 ⟶ 658:
'/D "attempting to add an entry for a Rosetta Code demonstration."'
/*stick a fork in it, we're all done. */</
{{out|output|text= is identical to the 1<sup>st</sup> REXX version.}} <br><br>
=={{header|Ruby}}==
{{libheader|win32-utils}}
<
logger = Win32::EventLog.new
logger.report_event(:event_type => Win32::EventLog::INFO, :data => "a test event log entry")</
Instructions on setting up an Event Source is [http://rubyforge.org/docman/view.php/85/1734/mc_tutorial.html here]
=={{header|Rust}}==
<syntaxhighlight lang="rust">
#[cfg(windows)]
mod bindings {
::windows::include_bindings!();
}
#[cfg(windows)]
use bindings::{
Windows::Win32::Security::{
GetTokenInformation, OpenProcessToken, PSID, TOKEN_ACCESS_MASK, TOKEN_INFORMATION_CLASS,
TOKEN_USER,
},
Windows::Win32::SystemServices::{
GetCurrentProcess, OpenEventLogA, ReportEventA, ReportEvent_wType, HANDLE, PSTR,
},
};
#[cfg(windows)]
fn main() -> windows::Result<()> {
let ph = unsafe { GetCurrentProcess() };
let mut th: HANDLE = HANDLE(0);
unsafe { OpenProcessToken(ph, TOKEN_ACCESS_MASK::TOKEN_QUERY, &mut th) }.ok()?;
// Determine the required buffer size, ignore ERROR_INSUFFICIENT_BUFFER
let mut length = 0_u32;
unsafe {
GetTokenInformation(
th,
TOKEN_INFORMATION_CLASS::TokenUser,
std::ptr::null_mut(),
0,
&mut length,
)
}
.ok()
.unwrap_err();
// Retrieve the user token.
let mut token_user_bytes = vec![0u8; length as usize];
unsafe {
GetTokenInformation(
th,
TOKEN_INFORMATION_CLASS::TokenUser,
token_user_bytes.as_mut_ptr().cast(),
length,
&mut length,
)
}
.ok()?;
// Extract the pointer to the user SID.
let user_sid: PSID = unsafe { (*token_user_bytes.as_ptr().cast::<TOKEN_USER>()).User.Sid };
// use the Application event log
let event_log_handle = unsafe { OpenEventLogA(PSTR::default(), "Application") };
let mut event_msg = PSTR(b"Hello in the event log\0".as_ptr() as _);
unsafe {
ReportEventA(
HANDLE(event_log_handle.0), //h_event_log: T0__,
ReportEvent_wType::EVENTLOG_WARNING_TYPE, // for type use EVENTLOG_WARNING_TYPE w_type: u16,
5, // for category use "Shell" w_category: u16,
1, // for ID use 1 dw_event_id: u32,
user_sid, // lp_user_sid: *mut c_void,
1, // w_num_strings: u16,
0, // dw_data_size: u32,
&mut event_msg, // lp_strings: *mut PSTR,
std::ptr::null_mut(), // lp_raw_data: *mut c_void,
)
}
.ok()?;
Ok(())
}
#[cfg(not(windows))]
fn main() {
println!("Not implemented");
}
</syntaxhighlight>
add this to the build.rs:
<syntaxhighlight lang="rust">
fn main() {
#[cfg(windows)]
{
windows::build!(Windows::Win32::SystemServices::{GetCurrentProcess, ReportEventA, OpenEventLogA, ReportEvent_wType, HANDLE, PSTR},
Windows::Win32::Security::{OpenProcessToken, GetTokenInformation, TOKEN_ACCESS_MASK, TOKEN_INFORMATION_CLASS, TOKEN_USER, PSID});
}
}
</syntaxhighlight>
And this to cargo.toml:
<syntaxhighlight lang="rust">
[target.'cfg(windows)'.dependencies]
windows = "0.7.0"
[target.'cfg(windows)'.build-dependencies]
windows = "0.7.0"
</syntaxhighlight>
=={{header|Scala}}==
The following works on Windows 10 with elevated (administrative) permission:
<
import sys.process._
Line 667 ⟶ 781:
println(s"\nSuccessfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")
}</
=={{header|Standard ML}}==
<syntaxhighlight lang="standard ml">
OS.Process.system "logger \"Log event\" " ;
</syntaxhighlight>
From MS Windows to MS Windows, taken from C:
<syntaxhighlight lang="standard ml">
OS.Process.system "EventCreate /t WARNING /id 458 /l APPLICATION /so SomeSource /d \"Settastring\"" ;
</syntaxhighlight>
=={{header|Tcl}}==
{{libheader|TWAPI}}
<
# This command handles everything; use “-type error” to write an error message
twapi::eventlog_log "My Test Event" -type info</
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Sub write_event(event_type,msg)
Set objShell = CreateObject("WScript.Shell")
Line 704 ⟶ 823:
Call write_event("INFORMATION","This is a test information.")
</syntaxhighlight>
=={{header|Wren}}==
{{trans|Go}}
This embedded program is untested as I no longer have a working Windows machine but should work when run with administrative privileges - what can possibly go wrong?
<syntaxhighlight lang="wren">/* Write_to_Windows_event_log.wren */
class Windows {
foreign static eventCreate(args)
}
var args = [
"/T", "INFORMATION", "/ID", "123", "/L", "APPLICATION",
"/SO", "Wren", "/D", "\"Rosetta Code Example\""
].join(" ")
Windows.eventCreate(args)</syntaxhighlight>
<br>
Now embed this script in the following C program, compile and run it.
<syntaxhighlight lang="c">/* gcc Write_to_Windows_event_log.c -o Write_to_Windows_event_log -lwren -lm */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "wren.h"
/* C <=> Wren interface functions */
void C_eventCreate(WrenVM* vm) {
const char *args = wrenGetSlotString(vm, 1);
char command[strlen(args) + 13];
strcpy(command, "EventCreate ");
strcat(command, args);
system(command);
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Windows") == 0) {
if (isStatic && strcmp(signature, "eventCreate(_)") == 0) return C_eventCreate;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "Write_to_Windows_event_log.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}</syntaxhighlight>
=={{header|zkl}}==
{{trans|Clojure}}
<
{{out}}
<pre>
Line 714 ⟶ 937:
0
</pre>
{{omit from|6502 Assembly|Windows has never been made for this hardware (not that I know of anyway)}}
{{omit from|68000 Assembly|Windows has never been made for this hardware (not that I know of anyway)}}
{{omit from|Lotus 123 Macro Scripting|Would overwrite the log file}}
{{omit from|Mathematica}}
{{omit from|Maxima}}
{{omit from|MIPS Assembly|Windows has never been made for this hardware (not that I know of anyway)}}
{{omit from|PARI/GP}}
{{omit from|PostScript}}
{{omit from|Retro|No access to Windows APIs}}
{{omit from|TI-83 BASIC|Cannot run on Windows}}
{{omit from|Z80 Assembly|Windows has never been made for this hardware (not that I know of anyway)}}
{{omit from|zkl}}
{{omit from|ZX Spectrum Basic|Microdrive access is slow, and there is no real time clock, so event logging is not usually done}}
|