Skip to main content
KBY Technologies Logo

Write Mac Script Logs With logger and Find Them Again With log show

Can't tell if a Mac script ran? Write lines with logger and a prefix, then search them with log show and eventMessage, tested on a spare Mac first.

KBY Technologies10 min readTier L115 min
Write Mac Script Logs With logger and Find Them Again With log show

Underlined words are defined in the KBY Lexicon. Tap or click one to see what it means.

To make a Mac script’s progress searchable, write each line with logger and put a fixed prefix in the message text. Find the lines afterwards with log show --last 30m --predicate 'eventMessage CONTAINS "kby-example"', run as an administrator.

The prefix matters because the logger manual page says -t marks each line with a tag, but it does not say how the unified log displays that tag. A prefix in the message is something you can always search for. Test the helper on a spare Mac before it reaches the fleet, and record how your version displays the lines.

#How it usually goes when a Mac script runs unseen

Most fleet scripts report in one of two ways. Some print with echo and rely on the management tool to keep the output. Others append to a file such as /var/log/example.log that nobody opens until something has already gone wrong.

Both break down in the same places. Output from a script run by an MDM, or by a LaunchDaemon as described in running a root script at boot or on a schedule, is only as good as whatever captures it. A private log file needs its own rotation, its own permissions and its own collection step. Lines from ten scripts end up in ten formats, with no shared way to ask what happened on one Mac between two times.

The macOS system log already solves most of this. Apple’s logger utility is, in its own words, a shell command interface to the syslog(3) system log module, and the log command reads the system-wide log datastore back. Your scripts can write to the same place the rest of the system does, and an engineer on a test Mac can query it with one command.

#What to do instead: one log function and one searchable prefix

The better workflow gives every script a single log function. Each line carries a fixed prefix that names the script, and each error is written at a different priority from routine progress. Reading the lines back is a time window plus a text filter.

Three documented behaviours shape the design.

  • Priority. logger -p accepts a numeric priority or a facility.level pair, and the default is user.notice. Using user.error for failures gives you a second way to separate them from progress.
  • Standard input. If you give no message and no -f file, logger logs its standard input. That lets you send a command’s output into the log with a pipe.
  • Default levels only. The log show page says its output contains only default-level messages unless --info or --debug is given. If a line you wrote at a lower priority is missing, add --info before you suspect the script.

The manual pages do not map each priority to a unified-log level, so treat the first bullet as a design aim and confirm the mapping on your own test Mac, as the validation section below does.

#Setting it up in a script

Add the helper near the top of each script, after the shebang. The function uses only syntax found in the 3.2 manual page, which is the shell at /bin/bash; writing Mac Bash scripts for the Bash 3.2 in /bin/bash explains why that matters.

1#!/bin/bash
2
3LOG_TAG="kby-example"
4
5# usage: log notice "message"   or   log error "message"
6log() {
7  level="$1"
8  shift
9  /usr/bin/logger -t "$LOG_TAG" -p "user.$level" "$LOG_TAG: $*"
10}
11
12# send a command's output into the log, one line per line
13log_output() {
14  /usr/bin/sed "s/^/$LOG_TAG: /" | /usr/bin/logger -t "$LOG_TAG" -p user.notice
15}
16
17log notice "start"
18
19if [ -d "/Applications/Example.app" ]; then
20  log notice "Example.app is present"
21else
22  log error "Example.app is missing"
23fi
24
25/bin/ls -l /Applications 2>&1 | log_output
26
27log notice "end"

Each part has a reason.

  1. The prefix is repeated inside the message. The -t tag replaces the default login-name marker, but the pages fetched do not say where the unified log shows it. The prefix inside the text is searchable whichever way it is displayed. It also means the message never begins with a hyphen. The synopsis puts options before the message, so a leading hyphen is a risk worth designing out.
  2. "$*" joins the arguments. The Bash manual says "$*" expands to one word with the parameters separated by the first character of IFS, which by default is a space. The whole message arrives as one argument.
  3. Full paths. A script started by a LaunchDaemon or an MDM may not have the PATH you test with. Using /usr/bin/logger removes the question. Confirm the path on a test Mac with command -v logger.
  4. The pipe helper reads standard input. With no message given, logger logs what it receives. The sed step puts the prefix on every line first.
  5. Start and end lines. A run that logged “start” but never “end” died partway. That is the simplest evidence a script can leave.

Following along? Tap a step’s number to tick it off.

The helper does not change how the script stops on failure. Pair it with your usual error handling. A pipeline’s return status is that of its last command unless pipefail is set, so the ls | log_output line above reports the status of the log helper, not of ls.

If the script runs as root on behalf of a person, remember the helper logs as root. Running a command as the logged-in user from a root Mac script covers the user-side steps, and each of those deserves its own log line.

Close-up view of a developer typing code on a keyboard with a computer screen showing scripts.
Photo by Jakub Zerdzicki on Pexels

#Keeping it safe on a production Mac

Logging is low risk, but three habits keep it that way.

  • Never log secrets. A line written to the system log is read by anyone who can run log show on that Mac,. Log that a token was found, not its value. Do not log whole command lines that contain a password or key.
  • Keep reading privileged. The log manual page says some commands require root privileges. Run log show with sudo on a managed Mac, and give that right only to engineers who already administer it.
  • Use a test tag first. Developing against the production prefix pollutes the searches your colleagues rely on. Use a clearly temporary prefix, such as kby-example-test, until the script is ready.

Treat the system log as a diagnostic aid, not an audit record. The pages fetched give no retention period, so check how far back log show reaches on your own Macs before you promise anyone a history. If an audit trail matters, collect the lines with the tool you already use for that purpose.

#Checking it worked on a test Mac

Do this on a spare Mac or virtual machine before any script goes to the fleet. Each step proves one thing.

  1. Syntax. Run /bin/bash -n ./script.sh. The -n option reads commands without running them. Expect no output and exit status 0.
  2. A single line. Run /usr/bin/logger -t kby-example-test "kby-example-test: hello". Expect no output and exit status 0; the manual says logger exits greater than 0 on error.
  3. Find it. Run sudo log show --last 5m --predicate 'eventMessage CONTAINS "kby-example-test"'. Expect one entry whose message contains your text. Note which column shows the process and whether the tag appears anywhere. That observation is the answer the manual pages do not give you.
  4. The error priority. Run the script’s error branch, then repeat the search with and without --info. If the error line appears without --info and a notice line does not, you have measured the mapping. Write the result in your team’s script standard.
  5. Piped output. Run the ls example and confirm each output line carries the prefix.
  6. The shell. Run /bin/bash --version and expect a GNU bash 3.2 version line.

The same predicate keys are what you will use later, including process, messageType and subsystem. Run log help predicates for the list on your macOS version. For the other side of the job, sorting a noisy log into what matters, see silencing chatty login window errors with launchd log triage.

#What goes wrong with script logging

  • The line is missing. The search window is too short, the line was written below the default level and --info was not set, or the predicate text does not match. Widen --last, add --info, then simplify the predicate to the prefix alone.
  • The search returns other people’s lines. The prefix is too generic. Use the script’s name, not a word like “script” or “install”.
  • A message that starts with a hyphen may be read as an option. The prefix inside the text prevents this. Do not log bare variable values.
  • A quoted message splits or loses text. Unquoted $* in the helper would pass several arguments. Keep the double quotes.
  • The status is wrong after a pipe. As above, a pipeline reports its last command unless pipefail is on. Check the status of the command you care about separately.
  • Time zones confuse the timeline. The log show page says output uses the time zone recorded when the entry was written unless --timezone is given. Add --timezone local when comparing with a person’s account of events.
A person is typing code on a laptop, focusing on the screen with programming script.
Photo by Lukas Blazek on Pexels

#Backing out a bad script version

Log lines are not a state change you can undo, and the system log offers no per-line edit. Recovery is about the script and the people reading it.

  1. Unassign the new script version in your management tool and reassign the previous version to the same group.
  2. Search the test prefix and the production prefix separately, so test lines are not mistaken for fleet evidence.
  3. If a script logged something sensitive, stop that version first. Then ask your security contact how to handle the entry, because removal from the log is not covered by the pages used here and should not be improvised.
  4. Confirm recovery by finding a “start” and “end” pair from the previous version on each pilot Mac.

#How to tell it worked across the fleet

Measure the work it saves, using your own numbers. Nothing here has a published benchmark.

  • Time to answer. Pick five recent “did the script run?” questions and time how long each took before the change. Time the same kind of question afterwards, using one log show search.
  • Complete runs. On a pilot group, count “start” lines that have a matching “end”. A gap is a run that died, which was invisible before.
  • Error rate. Count error-priority lines per script per week. A rise at first is expected, because hidden failures become visible. It should then fall as causes are fixed.
  • Review cadence. Check one script’s lines monthly, and again after each major macOS release, because the log options and behaviour are Apple’s to change.

#Before you roll out script logging

  • Every script has the same log helper and a unique prefix.
  • No log line contains a password, token, key or personal data.
  • The syntax check, single-line test and predicate search have passed on a test Mac.
  • You have recorded how the tag and each priority appear on your macOS version.
  • Only engineers who administer the Mac can run log show on it.
  • The previous script version is ready to reassign.

The next safe decision is a pilot group of a few Macs with one script. Look at the lines it writes for a week, fix the noisy or missing ones, then widen the group.

About this page

Credited to

Dates

Published

Sources

This page lists no external sources.

Corrections

No corrections are listed for this page. Some review sweeps corrected pages without naming each one; those are in the corrections log.

Found this useful? Follow KBY for more like it.

Reader Interaction

Comments

Add a thoughtful note on Write Mac Script Logs With logger and Find Them Again With log show. Comments are checked for spam and held for moderation before appearing.

Loading comments...

More from KBY that goes with this article.

Discover more

Was this useful?

Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.

Operate smarter, with fewer recurring tickets.

Receive new operational playbooks, incident-prevention guidance, automation scripts and recovery runbooks.