Skip to content

Commit df062d4

Browse files
G.S. HirparaG.S. Hirpara
authored andcommitted
Removed old log mechanism in favor of captured stdout so that both the script server and susubprocess modes use the same log mechanism
1 parent 433fd37 commit df062d4

2 files changed

Lines changed: 74 additions & 19 deletions

File tree

vangard/commands/BaseCommand.py

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,6 @@ def exec_remote_script(
102102
"scriptFile": script_path,
103103
"args": mark_args
104104
}
105-
106105

107106
print(f"Sending script to DAZ Script Server: {url}")
108107
print(f" payload: {json.dumps(payload, indent=2)}")
@@ -117,19 +116,25 @@ def exec_remote_script(
117116
timeout = 30
118117
with urllib.request.urlopen(req, timeout=timeout) as response:
119118
result = response.read().decode("utf-8")
120-
print(f"DAZ Script Server response: {result}")
119+
BaseCommand._print_script_output(result)
121120

122121
else:
123-
print(os.environ['DAZ_ROOT'])
124-
125122
daz_root = os.getenv("DAZ_ROOT")
126123
daz_args = os.getenv("DAZ_ARGS", "")
127124

128125
# Build command as a list for cross-platform compatibility
129126
command_list = [daz_root]
130127

128+
# Inject _log_file if DAZ_LOG_FILE env var is set, giving subprocess
129+
# mode a configurable (non-hardcoded) file for diagnostic output.
130+
effective_vars = dict(script_vars) if script_vars is not None else {}
131+
daz_log_file = os.getenv("DAZ_LOG_FILE")
132+
if daz_log_file:
133+
effective_vars["_log_file"] = daz_log_file
134+
print(f"Script log output will be written to: {daz_log_file}")
135+
131136
# Add script arguments
132-
mark_args = json.dumps(script_vars) if script_vars is not None else ""
137+
mark_args = json.dumps(effective_vars) if effective_vars else ""
133138
if mark_args:
134139
command_list.extend(["-scriptArg", mark_args])
135140

@@ -152,6 +157,34 @@ def exec_remote_script(
152157
subprocess.Popen(command_list, shell=False)
153158

154159

160+
@staticmethod
161+
def _print_script_output(raw: str) -> None:
162+
"""
163+
Parses and displays output returned by the DAZ Script Server.
164+
165+
Scripts emit structured JSON log lines via print() (one per line).
166+
Each line is attempted as JSON; if it parses as a log entry (has an
167+
'event_type' key) it is displayed in a readable format. Lines that
168+
are not valid JSON are printed as-is.
169+
"""
170+
for line in raw.splitlines():
171+
line = line.strip()
172+
if not line:
173+
continue
174+
try:
175+
entry = json.loads(line)
176+
if "event_type" in entry:
177+
level = entry.get("event_type", "INFO")
178+
source = entry.get("source", "")
179+
msg = entry.get("message", "")
180+
status = entry.get("status", "")
181+
detail = f" [{status}]" if status else ""
182+
print(f"[{level}] {source}{detail}: {msg}" if msg else f"[{level}] {json.dumps(entry)}")
183+
else:
184+
print(line)
185+
except (json.JSONDecodeError, ValueError):
186+
print(line)
187+
155188
@staticmethod
156189
def to_dict(args: argparse.Namespace, exclude: Optional[Set[str]] = None) -> Dict[str, Any]:
157190
"""

vangard/scripts/DazLoggingUtils.dsa

Lines changed: 36 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -86,18 +86,20 @@ function close_log() {
8686
/**
8787
* Initializes script utilities. This includes:
8888
* - Setting the global log source name (`s_logSourceName`).
89-
* - Initializing the log file (hardcoded to 'C:/Temp/razor.log', append mode).
9089
* - Updating modifier key states.
91-
* - Parsing script arguments (expected to be a JSON string in `App.scriptArgs[0]`) and logging them.
90+
* - Parsing script arguments (expected to be a JSON string in `App.scriptArgs[0]`
91+
* in subprocess mode, or via `getArguments()` in server mode).
92+
* - Optionally opening a log file if the parsed args contain a `_log_file` key.
93+
* This is the only supported way to enable file logging; there is no hardcoded
94+
* default path.
95+
*
9296
* @param {string} log_source_id - The identifier to use as the source for log entries.
9397
* @returns {object | null} The parsed script arguments object, or `null` if parsing fails or no arguments.
9498
*/
9599
function init_script_utils(log_source_id) {
96100

97101
s_logSourceName = log_source_id;
98102

99-
init_log('C:/Temp/razor.log', false);
100-
101103
// If the "Action" global transient is defined, and its the correct type
102104
if( typeof( Action ) != "undefined" && Action.inherits( "DzScriptAction" ) ){
103105
// If the current key sequence for the action is not pressed
@@ -112,9 +114,16 @@ function init_script_utils(log_source_id) {
112114
args = getArguments()[0];
113115
if (args == undefined) {
114116
args = App.scriptArgs[0];
115-
rv = JSON.parse(args);
117+
rv = JSON.parse(args);
116118
} else {
117-
rv = args;
119+
rv = args;
120+
}
121+
122+
// Optional file logging: only enabled when the caller passes `_log_file`
123+
// in the script arguments (e.g. via the DAZ_LOG_FILE environment variable
124+
// on the Python side). No hardcoded default path is used.
125+
if (rv != null && rv['_log_file'] != undefined) {
126+
init_log(rv['_log_file'], false);
118127
}
119128

120129
return rv;
@@ -129,18 +138,23 @@ function close_script_utils() {
129138
}
130139

131140
/**
132-
* Logs an event to the initialized log file.
133-
* The event is logged as a JSON string containing source, timestamp, event type, name, and additional info.
141+
* Logs an event by printing a JSON-encoded log line to stdout and, if a log
142+
* file is open, writing it there as well.
143+
*
144+
* In DAZ Script Server mode the script's stdout is captured by the server and
145+
* returned to the Python caller as part of the HTTP response, so every call to
146+
* this function produces a structured result that the caller can parse.
147+
*
148+
* In subprocess mode stdout is not piped back to Python, but if a log file was
149+
* configured via the `_log_file` script argument (or an explicit `init_log`
150+
* call) the entry is also written there.
151+
*
134152
* @param {string} event_type - The type of the event (e.g., "INFO", "ERROR").
135153
* @param {string} event_name - A name or category for the event.
136-
* @param {object} [event_info=null] - An optional object containing additional key-value pairs to include in the log entry.
154+
* @param {object} [event_info=null] - An optional object with additional key-value pairs to include.
137155
* @returns {void}
138156
*/
139157
function log_event(event_type, event_name, event_info) {
140-
if (log_file == null || !log_file.isOpen()) {
141-
return;
142-
}
143-
144158
var base_message = {
145159
'source': s_logSourceName,
146160
'dtg': Date.now(),
@@ -157,7 +171,15 @@ function log_event(event_type, event_name, event_info) {
157171
}
158172
}
159173

160-
log_file.writeLine(JSON.stringify(base_message));
174+
var json_line = JSON.stringify(base_message);
175+
176+
// Always emit to stdout so server mode captures it as a return value.
177+
print(json_line);
178+
179+
// Also write to the log file if one was opened (subprocess / explicit use).
180+
if (log_file != null && log_file.isOpen()) {
181+
log_file.writeLine(json_line);
182+
}
161183
}
162184

163185
/**

0 commit comments

Comments
 (0)