Write to Windows event log: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(15 intermediate revisions by 10 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">
<lang AWK>
# syntax: GAWK -f WRITE_TO_WINDOWS_EVENT_LOG.AWK
BEGIN {
Line 216 ⟶ 226:
}
function error(message) { printf("error: %s\n",message) ; errors++ }
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 224 ⟶ 234:
=={{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 236 ⟶ 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 246 ⟶ 256:
{{works with|BBC BASIC for Windows}}
Writes to the Application Log:
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"COMLIB"
PROC_cominitlcid(1033)
Line 253 ⟶ 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">
<lang C>
#include<stdlib.h>
#include<stdio.h>
Line 274 ⟶ 284:
return 0;
}
</syntaxhighlight>
</lang>
Invocation and output on console :
<pre>
Line 282 ⟶ 292:
</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.
<syntaxhighlight lang="csharp">using System.Diagnostics;
 
namespace RC
{
internal class Program
{
public static void Main()
{
string sSource = "Sample App";
string sLog = "Application";
string sEvent = "Hello from RC!";
 
if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource, sLog);
 
EventLog.WriteEntry(sSource, sEvent);
EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Information);
}
}
}</syntaxhighlight>
 
=={{header|C++}}==
{{trans|C}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <sstream>
 
Line 305 ⟶ 338:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
In Windows Vista and later or Windows Server 2003, you must have administrative privileges to execute this code.
<lang csharp>using System.Diagnostics;
 
namespace RC
{
internal class Program
{
public static void Main()
{
string sSource = "Sample App";
string sLog = "Application";
string sEvent = "Hello from RC!";
 
if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource, sLog);
 
EventLog.WriteEntry(sSource, sEvent);
EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Information);
}
}
}</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(use 'clojure.java.shell)
(sh "eventcreate" "/T" "INFORMATION" "/ID" "123" "/D" "Rosetta Code example")</langsyntaxhighlight>
 
=={{header|D}}==
{{trans|Kotlin}}
<langsyntaxhighlight Dlang="d">import std.process;
import std.stdio;
 
Line 347 ⟶ 357:
writeln("Failed to execute command, status=", cmd.status);
}
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program WriteToEventLog;
 
{$APPTYPE CONSOLE}
Line 375 ⟶ 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|Go}}==
This works on Windows 10 with administrative privileges.
<langsyntaxhighlight lang="go">package main
 
import (
Line 401 ⟶ 411:
fmt.Println(err)
}
}</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
Line 432 ⟶ 442:
}
}
}</langsyntaxhighlight>
 
=={{header|Julia}}==
Run as an administrator.
<langsyntaxhighlight lang="julia">
cmd = "eventcreate /T INFORMATION /ID 123 /D \"Rosetta Code Write to Windows event log task example\""
Base.run(`$cmd`)
</syntaxhighlight>
</lang>
 
 
=={{header|Kotlin}}==
The following works on Windows 10 with administrative privileges:
<langsyntaxhighlight lang="scala">// version 1.1.4-3
 
fun main(args: Array<String>) {
Line 455 ⟶ 464:
 
Runtime.getRuntime().exec(command)
}</langsyntaxhighlight>
 
=={{header|Lingo}}==
{{libheader|Shell xtra}}
<langsyntaxhighlight Lingolang="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)</langsyntaxhighlight>
 
=={{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:
<lang PicoLisp>: (call 'logger "This is a test")
-> T
 
: (call 'logger "This" 'is "another" 'test)
-> T</lang>
 
=={{header|Perl}}==
Line 477 ⟶ 478:
The Win32::EventLog module has the Report method to write in the EventLog
 
<langsyntaxhighlight lang="perl">
use strict;
use warnings;
Line 494 ⟶ 495:
};
$handle->Report($event);
</syntaxhighlight>
</lang>
 
=={{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.
<lang Phix>system(`eventcreate /T INFORMATION /ID 123 /D "Rosetta Code Write to Windows event log task example"`)</lang>
<!--<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 503 ⟶ 509:
</pre>
 
=={{header|PureBasicPicoLisp}}==
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:
<lang PureBasic>Procedure WriteToLog(Event_App$,EventMessage$,EvenetType,Computer$)
<syntaxhighlight lang="picolisp">: (call 'logger "This is a test")
-> T
 
: (call 'logger "This" 'is "another" 'test)
Protected wNumStrings.w, lpString=@EventMessage$, lReturnX, CMessageTyp, lparray
-> T</syntaxhighlight>
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</lang>
 
=={{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 532 ⟶ 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>
Line 538 ⟶ 536:
 
===Source and event log existing===
<langsyntaxhighlight 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 ' +
Line 544 ⟶ 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>
</lang>
{{out|output}}
<pre>
Line 550 ⟶ 548:
</pre>
===New event log===
<langsyntaxhighlight 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 ' +
Line 558 ⟶ 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>
</lang>
{{out|output}}
<pre>
Line 564 ⟶ 562:
</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 569 ⟶ 582:
{{libheader|PyWin32}}
 
<langsyntaxhighlight Pythonlang="python">import win32api
import win32con
import win32evtlog
Line 587 ⟶ 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|Scala}}==
The following works on Windows 10 with elevated (administrative) permission:
<lang Scala>object RegisterWinLogEvent extends App {
 
=={{header|Raku}}==
import sys.process._
(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.)
def eventCreate= Seq("EVENTCREATE", "/T", "SUCCESS", "/id", "123", "/l", "APPLICATION", "/so", "Scala RegisterWinLogEvent", "/d", "Rosetta Code Example" ).!!
 
<syntaxhighlight lang="raku" line>given $*DISTRO {
println(eventCreate)
when .is-win {
 
my $cmd = "eventcreate /T INFORMATION /ID 123 /D \"Bla de bla bla bla\"";
println(s"\nSuccessfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")
run($cmd);
 
}
}</lang>
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}}==
Line 614 ⟶ 633:
 
===annotated===
<langsyntaxhighlight lang="rexx">/*REXX program writes a "record" (event) to the (Microsoft) Windows event log. */
 
eCMD = 'EVENTCREATE' /*name of the command that'll be used. */
Line 626 ⟶ 645:
eCMD '/T' type "/ID" id '/L' logName "/SO" source '/D' desc
 
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output}}
<pre>
Line 633 ⟶ 652:
 
===bare bones===
<langsyntaxhighlight lang="rexx">/*REXX program writes a "record" (event) to the (Microsoft) Windows event log. */
/* [↓] cmd options have extra spacing.*/
 
Line 639 ⟶ 658:
'/D "attempting to add an entry for a Rosetta Code demonstration."'
 
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{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 680 ⟶ 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 690 ⟶ 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