How do you use logging in scripts in Sierra's new unified logging system?

c_kay
New Contributor III

So I use the 'logger' command a lot in my scripts to log useful info and errors.

Before Sierra I could log something to syslog like this

logger -s -p local0.notice -t my_script "Some message to log"

And you could find that message in /var/log/system.log by doing this

grep my_script /var/log/system.log

Now with 10.12 the logger command doesn't log to system.log any more and uses this new unified logging system

Now there's the 'log' command that you can use to query the unified logging system and you can search for text in messages but I can't find anyway to search on the tags (-t option in logger)

Has anyone come up with method of logging info in scripts that can be easily searched for 10.12?

2 REPLIES 2

donmontalvo
Esteemed Contributor III

Not sure what to think about this new system.

"The unified logging system stores messages in memory and in a data store, rather than writing to te...

We've been using tee to output to /Library/Logs, so we get display and output to a file:

# echo $(date) | tee /Library/Logs/date.log
Fri Feb 3 03:18:55 PST 2017
# cat /Library/Logs/date.log
Fri Feb 3 03:18:55 PST 2017

Easier than fishing for something that Apple is making tougher to find.

https://en.wikipedia.org/wiki/Tee_(command)

--
https://donmontalvo.com

dan-snelson
Valued Contributor II

@c.kay We write everything to our own client-side log, which we then upload to the JSS via the API as needed.

Here's a snippet from our "functions.sh" which we write client-side (i.e., /path/to/client-side/functions.sh) and is then source'd in all our other scripts:

#!/bin/sh
####################################################################################################
#
# LOGGING
#
####################################################################################################

# Variables

logFile="/var/log/com.company.division.log"

# Check for / create logFile
if [ ! -f "${logFile}" ]; then
    # logFile not found; Create logFile
    /usr/bin/touch "${logFile}"
fi

function ScriptLog() { # Re-direct logging to the log file ...

    exec 3>&1 4>&2        # Save standard output and standard error
    exec 1>>"${logFile}"    # Redirect standard output to logFile
    exec 2>>"${logFile}"    # Redirect standard error to logFile

    NOW=`date +%Y-%m-%d %H:%M:%S`    
    /bin/echo "${NOW}" " ${1}" >> ${logFile}

}


function jssLog() { # Re-direct logging to the JSS

    ScriptLog "${1}"

    exec 1>&3 2>&4
    /bin/echo >&1 ${1}

}

Then, in all our other scripts we include …

source /path/to/client-side/functions.sh

… and …

ScriptLog "Comment to write to client-side log goes inside these quotes"

… and / or …

jssLog "Comment to write back to the JSS script results goes inside these quotes"

Clear as mud?