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.

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 macOS 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 -paccepts a numeric priority or afacility.levelpair, and the default isuser.notice. Usinguser.errorfor failures gives you a second way to separate them from progress. - Standard input. If you give no message and no
-ffile,loggerlogs its standard input. That lets you send a command’s output into the log with a pipe. - Default levels only. The
log showpage says its output contains only default-level messages unless--infoor--debugis given. If a line you wrote at a lower priority is missing, add--infobefore you suspect the script.
The manual pages do not map each syslog 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 Bash 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.
- The prefix is repeated inside the message. The
-ttag 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. "$*"joins the arguments. The Bash manual says"$*"expands to one word with the parameters separated by the first character ofIFS, which by default is a space. The whole message arrives as one argument.- Full paths. A script started by a LaunchDaemon or an MDM may not have the PATH you test with. Using
/usr/bin/loggerremoves the question. Confirm the path on a test Mac withcommand -v logger. - The pipe helper reads standard input. With no message given,
loggerlogs what it receives. Thesedstep puts the prefix on every line first. - 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.

#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 showon 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
logmanual page says some commands require root privileges. Runlog showwithsudoon 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.
- Syntax. Run
/bin/bash -n ./script.sh. The-noption reads commands without running them. Expect no output and exit status 0. - A single line. Run
/usr/bin/logger -t kby-example-test "kby-example-test: hello". Expect no output and exit status 0; the manual saysloggerexits greater than 0 on error. - 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. - The error priority. Run the script’s error branch, then repeat the search with and without
--info. If the error line appears without--infoand a notice line does not, you have measured the mapping. Write the result in your team’s script standard. - Piped output. Run the
lsexample and confirm each output line carries the prefix. - The shell. Run
/bin/bash --versionand 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
--infowas 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
pipefailis on. Check the status of the command you care about separately. - Time zones confuse the timeline. The
log showpage says output uses the time zone recorded when the entry was written unless--timezoneis given. Add--timezone localwhen comparing with a person’s account of events.

#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.
- Unassign the new script version in your management tool and reassign the previous version to the same group.
- Search the test prefix and the production prefix separately, so test lines are not mistaken for fleet evidence.
- 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.
- 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 showsearch. - 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
logoptions and behaviour are Apple’s to change.
#Before you roll out script logging
- Every script has the same
loghelper 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 showon 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
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.
Recommended reading
More from KBY that goes with this article.
Related articles
Automation & Scripting
Run a Command as the Logged-In User From a Root Mac Script
Root MDM script needs to act as the Mac user? Find the console user with stat, then run launchctl asuser with sudo -u, with a read-back and a backup.
ReadSecurity
Device Code Phishing: Rogue Entra Devices in 305 Organisations Survive a Password Reset
Huntress found 468 rogue Entra ID device registrations in 305 organisations. A password reset does not remove them. How to find the devices and block the device code flow.
ReadSecurity
NCSC Urges Urgent Post-Quantum Migration Planning After NSA Advisory: What UK IT Teams Should Do
The NCSC says organisations with high-value data should work to its post-quantum timelines and finish priority actions by 2031. What to check first.
ReadDiscover more
Ops Playbook
- PlaybookMake Mac Admin Scripts Fail Loudly and Clean Up After Themselves With set, trap and mktemp
- PlaybookRun a Command as the Logged-In User From a Root Mac Script
- PlaybookWrite Mac Bash Scripts for the Bash 3.2 in /bin/bash, Not Your Homebrew Bash
- PlaybookRun a Root Script at Boot or on a Schedule With a macOS LaunchDaemon
Lexicon Definitions
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.



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.