Write to Windows event log: Difference between revisions

m
mNo edit summary
m (→‎{{header|Wren}}: Minor tidy)
 
(35 intermediate revisions by 19 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}}==
<langsyntaxhighlight lang="autohotkey">; By ABCza, http://www.autohotkey.com/board/topic/76170-function-send-windows-log-events/
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 ; PSID, ptr to user security ID
, UShort, 1 ; WORD, number of strings
, UInt, VarSetCapacity(pData) ; DWORD, data size
, PtrLPCtSTRs, &eventMessage ; LPCTSTR*, ptr to a buffer ...
, Ptr, (VarSetCapacity(pData)) ? &pData : 0 ) ; ptr to a buffer of binary data
Line 195 ⟶ 204:
; Return the number of characters copied.
return char_count
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f WRITE_TO_WINDOWS_EVENT_LOG.AWK
BEGIN {
write("INFORMATION",1,"Rosetta Code")
exit (errors == 0) ? 0 : 1
}
function write(type,id,description, cmd,esf) {
esf = errors # errors so far
cmd = sprintf("EVENTCREATE.EXE /T %s /ID %d /D \"%s\" >NUL",type,id,description)
printf("%s\n",cmd)
if (toupper(type) !~ /^(SUCCESS|ERROR|WARNING|INFORMATION)$/) { error("/T is invalid") }
if (id+0 < 1 || id+0 > 1000) { error("/ID is invalid") }
if (description == "") { error("/D is invalid") }
if (errors == esf) {
system(cmd)
}
return(errors)
}
function error(message) { printf("error: %s\n",message) ; errors++ }
</syntaxhighlight>
{{out}}
<pre>
EVENTCREATE.EXE /T INFORMATION /ID 1 /D "Rosetta Code" >NUL
</pre>
 
=={{header|Batch File}}==
The "EventCreate" command does the task.
<langsyntaxhighlight lang="dos">@echo off
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"</langsyntaxhighlight>
{{Out}}
<pre>>EventLog.BAT
Line 211 ⟶ 246:
></pre>
If you do not want the command to display its result or errors...
<langsyntaxhighlight lang="dos">@echo off
EventCreate /t ERROR /id 123 /l SYSTEM /so "A Batch File" /d "This is found in system log." 2>NUL 2>NUL&1
EventCreate /t WARNING /id 456 /l APPLICATION /so BlaBla /d "This is found in apps log" 2>NUL 2>NUL&1
::That "2>NUL 2>NUL&1" trick actually works in any command!</langsyntaxhighlight>
 
'''NOTE:''' This will (...or might) not work if you do not have administrator privileges.
Line 221 ⟶ 256:
{{works with|BBC BASIC for Windows}}
Writes to the Application Log:
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"COMLIB"
PROC_cominitlcid(1033)
Line 228 ⟶ 263:
PROC_releaseobject(WshShell%)
PROC_comexit</langsyntaxhighlight>
 
=={{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>
 
int main(int argC,char* argV[])
{
char str[1000];
if(argC!=5)
printf("Usage : %s < Followed by level, id, source string and description>",argV[0]);
else{
sprintf(str,"EventCreate /t %s /id %s /l APPLICATION /so %s /d \"%s\"",argV[1],argV[2],argV[3],argV[4]);
system(str);
}
return 0;
}
</syntaxhighlight>
Invocation and output on console :
<pre>
C:\rosettaCode>eventLog.exe WARNING 458 SOmeString "This is a joke"
 
SUCCESS: An event of type 'WARNING' was created in the 'APPLICATION' log with 'SOmeString' as the source.
</pre>
Microsoft does provide an C/C++ API for EventCreate, but as with everything Microsoft, it's so wonderfully convoluted, that I will just give a link to the [https://msdn.microsoft.com/en-us/library/aa363680(v=vs.85).aspx ReportEvent] example.
 
=={{header|C sharp}}==
In Windows Vista and later or Windows Server 2003, you must have administrative privileges to execute this code.
<langsyntaxhighlight lang="csharp">using System.Diagnostics;
 
namespace RC
Line 251 ⟶ 314:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{trans|C}}
<syntaxhighlight lang="cpp">#include <iostream>
#include <sstream>
 
int main(int argc, char *argv[]) {
using namespace std;
 
#if _WIN32
if (argc != 5) {
cout << "Usage : " << argv[0] << " (type) (id) (source string) (description>)\n";
cout << " Valid types: SUCCESS, ERROR, WARNING, INFORMATION\n";
} else {
stringstream ss;
ss << "EventCreate /t " << argv[1] << " /id " << argv[2] << " /l APPLICATION /so " << argv[3] << " /d \"" << argv[4] << "\"";
system(ss.str().c_str());
}
#else
cout << "Not implemented for *nix, only windows.\n";
#endif
 
return 0;
}</syntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(use 'clojure.java.shell)
(sh "eventcreate" "/T" "INFORMATION" "/ID" "123" "/D" "Rosetta Code example")</langsyntaxhighlight>
 
=={{header|D}}==
{{trans|Kotlin}}
<syntaxhighlight lang="d">import std.process;
import std.stdio;
 
void main() {
auto cmd = executeShell(`EventCreate /t INFORMATION /id 123 /l APPLICATION /so Dlang /d "Rosetta Code Example"`);
 
if (cmd.status == 0) {
writeln("Output: ", cmd.output);
} else {
writeln("Failed to execute command, status=", cmd.status);
}
}</syntaxhighlight>
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program WriteToEventLog;
 
{$APPTYPE CONSOLE}
Line 283 ⟶ 385:
begin
WriteLog('Message to log.');
end.</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<p>Bare bone writing to the Application Eventlog giving no event-ID and using the default event type (information.)</p>
<langsyntaxhighlight lang="fsharp">use log = new System.Diagnostics.EventLog()
log.Source <- "Sample Application"
log.WriteEntry("Entered something in the Application Eventlog!")</langsyntaxhighlight>
 
=={{header|PicoLispGo}}==
This works on Windows 10 with administrative privileges.
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:
<syntaxhighlight lang="go">package main
<lang PicoLisp>: (call 'logger "This is a test")
-> T
 
import (
: (call 'logger "This" 'is "another" 'test)
"fmt"
-> T</lang>
"os/exec"
)
 
func main() {
=={{header|PureBasic}}==
command := "EventCreate"
<lang PureBasic>Procedure WriteToLog(Event_App$,EventMessage$,EvenetType,Computer$)
args := []string{"/T", "INFORMATION", "/ID", "123", "/L", "APPLICATION",
"/SO", "Go", "/D", "\"Rosetta Code Example\""}
cmd := exec.Command(command, args...)
err := cmd.Run()
if err != nil {
fmt.Println(err)
}
}</syntaxhighlight>
 
=={{header|Java}}==
Protected wNumStrings.w, lpString=@EventMessage$, lReturnX, CMessageTyp, lparray
<syntaxhighlight lang="java">import java.io.BufferedReader;
Protected lprawdata=@EventMessage$, rawdata=Len(EventMessage$), Result
import java.io.IOException;
Protected lLogAPIRetVal.l = RegisterEventSource_(Computer$, Event_App$)
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
 
public class WriteToWindowsEventLog {
If lLogAPIRetVal
public static void main(String[] args) throws IOException, InterruptedException {
lReturnX = ReportEvent_(lLogAPIRetVal,EvenetType,0,CMessageTyp,0,wNumStrings,rawdata,lparray,lprawdata
String osName = System.getProperty("os.name").toUpperCase(Locale.ENGLISH);
DeregisterEventSource_(lLogAPIRetVal)
if (!osName.startsWith("WINDOWS")) {
Result=#True
System.err.println("Not windows");
EndIf
return;
}
 
Process process = Runtime.getRuntime().exec("EventCreate /t INFORMATION /id 123 /l APPLICATION /so Java /d \"Rosetta Code Example\"");
ProcedureReturn Result
process.waitFor(10, TimeUnit.SECONDS);
EndProcedure</lang>
int exitValue = process.exitValue();
System.out.printf("Process exited with value %d\n", exitValue);
if (exitValue != 0) {
InputStream errorStream = process.getErrorStream();
String result = new BufferedReader(new InputStreamReader(errorStream))
.lines()
.collect(Collectors.joining("\n"));
System.err.println(result);
}
}
}</syntaxhighlight>
 
=={{header|Julia}}==
Run as an administrator.
<syntaxhighlight lang="julia">
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:
<syntaxhighlight lang="scala">// version 1.1.4-3
 
fun main(args: Array<String>) {
val command = "EventCreate" +
" /t INFORMATION" +
" /id 123" +
" /l APPLICATION" +
" /so Kotlin" +
" /d \"Rosetta Code Example\""
 
Runtime.getRuntime().exec(command)
}</syntaxhighlight>
 
=={{header|Lingo}}==
{{libheader|Shell xtra}}
<syntaxhighlight lang="lingo">shell = xtra("Shell").new()
props = [:]
props["operation"] = "runas"
props["parameters"] = "/t INFORMATION /id 123 /l APPLICATION /so Lingo /d "&QUOTE&"Rosetta Code Example"&QUOTE
shell.shell_exec("EventCreate", props)</syntaxhighlight>
 
=={{header|Perl}}==
{{libheader|Win32&#58;&#58;EventLog}}
The Win32::EventLog module has the Report method to write in the EventLog
 
<syntaxhighlight lang="perl">
use strict;
use warnings;
 
use Win32::EventLog;
my $handle = Win32::EventLog->new("Application");
 
my $event = {
Computer => $ENV{COMPUTERNAME},
Source => 'Rosettacode',
EventType => EVENTLOG_INFORMATION_TYPE,
Category => 'test',
EventID => 0,
Data => 'a test for rosettacode',
Strings => 'a string test for rosettacode',
};
$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>
SUCCESS: An event of type 'INFORMATION' was created in the 'Application' log with 'EventCreate' as the source.
</pre>
 
=={{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:
<syntaxhighlight lang="picolisp">: (call 'logger "This is a test")
-> T
 
: (call 'logger "This" 'is "another" 'test)
-> T</syntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell"># Create Event Log object
$EventLog=new-object System.Diagnostics.EventLog("Application")
#Declare Event Source; must be 'registered' with Windows
Line 328 ⟶ 530:
 
# Write the event in the format "Event test",EventType,EventID
$EventLog.WriteEntry("My Test Event",$infoevent,70)</langsyntaxhighlight>
''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>
''Note2:'' See details on registering a new Event Source with Windows at [http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.registerdisplayname.aspx MSDN]
 
===Source and event log existing===
<syntaxhighlight lang="powershell">
$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 ' +
'his immediate release from jail and that he be allowed to run in the upcoming elections.'
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>
SUCCESS: The Lula Livre message (#FreeLula) has been recorded in the system log event.
</pre>
===New event log===
<syntaxhighlight lang="powershell">
$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 ' +
'his immediate release from jail and that he be allowed to run in the upcoming elections.'
New-EventLog -LogName 'Free Lula!' -Source '#FreeLula'
Limit-EventLog -OverflowAction 'OverWriteAsNeeded' -MaximumSize (64KB*13) -LogName 'Free Lula!'
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>
SUCCESS: The Lula Livre message (#FreeLula) has been recorded in the "Free Lula!" log event.
</pre>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">Procedure WriteToLog(Event_App$,EventMessage$,EvenetType,Computer$)
 
Protected wNumStrings.w, lpString=@EventMessage$, lReturnX, CMessageTyp, lparray
Protected lprawdata=@EventMessage$, rawdata=Len(EventMessage$), Result
Protected lLogAPIRetVal.l = RegisterEventSource_(Computer$, Event_App$)
 
If lLogAPIRetVal
lReturnX = ReportEvent_(lLogAPIRetVal,EvenetType,0,CMessageTyp,0,wNumStrings,rawdata,lparray,lprawdata
DeregisterEventSource_(lLogAPIRetVal)
Result=#True
EndIf
 
ProcedureReturn Result
EndProcedure</syntaxhighlight>
 
=={{header|Python}}==
Line 337 ⟶ 582:
{{libheader|PyWin32}}
 
<langsyntaxhighlight Pythonlang="python">import win32api
import win32con
import win32evtlog
Line 355 ⟶ 600:
 
win32evtlogutil.ReportEvent(applicationName, eventID, eventCategory=category,
eventType=myType, strings=descr, data=data, sid=my_sid)</langsyntaxhighlight>
 
=={{header|Racket}}==
Racket's logging facility creates windows events when running on Windows.
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(log-warning "Warning: nothing went wrong.")
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2020.01}}
There is not yet (that I am aware of) a native interface to the Windows logging functions, but Raku can shell out and run a console command just as easily as most of these other languages. It ''does'' have a native interface to the syslog functions under POSIX environments though.
 
(Same caveats as the others, needs to be run as administrator or with elevated privileges under Windows.)
 
<syntaxhighlight lang="raku" line>given $*DISTRO {
when .is-win {
my $cmd = "eventcreate /T INFORMATION /ID 123 /D \"Bla de bla bla bla\"";
run($cmd);
}
default { # most POSIX environments
use Log::Syslog::Native;
my $logger = Log::Syslog::Native.new(facility => Log::Syslog::Native::User);
$logger.info("[$*PROGRAM-NAME pid=$*PID user=$*USER] Just thought you might like to know.");
}
}</syntaxhighlight>
 
=={{header|REXX}}==
This was executed on a (Microsoft) Windows/XP PRO system.
<lang rexx>/*REXX program writes a "record" (event) to the (MS) Windows event log.*/
 
===annotated===
eCMD = 'EVENTCREATE'
<syntaxhighlight lang="rexx">/*REXX program writes a "record" (event) to the (Microsoft) Windows event log. */
type = 'INFORMATION' /*one of: ERROR WARNING INFORMATION */
id = 234 /*in range: 1 ───► 1000 (inclusive).*/
logName = 'APPLICATION'
source = 'REXX'
desc = 'attempting to add an entry for Rosetta Code demonstration.'
desc = '"' || desc '"' /*enclose DESCription in double quotes.*/
 
eCMD = '/TEVENTCREATE' type "/ID" id '/L' logName "/SO" source ' /D*name of the command that'll descbe used. */
type = 'INFORMATION' /*one of: ERROR WARNING INFORMATION */
id = 234 /*in range: 1 ───► 1000 (inclusive).*/
logName = 'APPLICATION' /*information about what this is. */
source = 'REXX' /* " " who's doing this. */
desc = 'attempting to add an entry for a Rosetta Code demonstration.'
desc = '"' || desc || '"' /*enclose description in double quotes.*/
 
eCMD '/T' type "/ID" id '/L' logName "/SO" source /*stick a fork in it honey, we're done.*/</lang>D' desc
 
'''output'''
/*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output}}
<pre>
SUCCESS: A 'INFORMATION' type event is created in the 'REXX' log/source.
</pre>
 
===bare bones===
<syntaxhighlight lang="rexx">/*REXX program writes a "record" (event) to the (Microsoft) Windows event log. */
/* [↓] cmd options have extra spacing.*/
 
'EVENTCREATE /T INFORMATION /ID 234 /L APPLICATION /SO REXX' ,
'/D "attempting to add an entry for a Rosetta Code demonstration."'
 
/*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
 
=={{header|Ruby}}==
{{libheader|win32-utils}}
<langsyntaxhighlight lang="ruby">require 'win32/eventlog'
logger = Win32::EventLog.new
logger.report_event(:event_type => Win32::EventLog::INFO, :data => "a test event log entry")</langsyntaxhighlight>
 
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:
<syntaxhighlight lang="scala">object RegisterWinLogEvent extends App {
 
import sys.process._
 
def eventCreate= Seq("EVENTCREATE", "/T", "SUCCESS", "/id", "123", "/l", "APPLICATION", "/so", "Scala RegisterWinLogEvent", "/d", "Rosetta Code Example" ).!!
 
println(eventCreate)
 
println(s"\nSuccessfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")
 
}</syntaxhighlight>
 
=={{header|Standard ML}}==
From bsd/linux/unix to log
<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}}
<langsyntaxhighlight lang="tcl">package require twapi
 
# This command handles everything; use “-type error” to write an error message
twapi::eventlog_log "My Test Event" -type info</langsyntaxhighlight>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Sub write_event(event_type,msg)
Set objShell = CreateObject("WScript.Shell")
Line 423 ⟶ 823:
 
Call write_event("INFORMATION","This is a test information.")
</syntaxhighlight>
</lang>
 
=={{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}}
<langsyntaxhighlight lang="zkl">zkl: System.cmd(0'|eventcreate "/T" "INFORMATION" "/ID" "123" "/D" "Rosetta Code example"|)</langsyntaxhighlight>
{{out}}
<pre>
Line 433 ⟶ 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|Swift|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}}
9,476

edits