Skip to content

Logging Analysis Scripts

The Audit Trail chapter covers what the Posit products record about users and servers. This chapter covers the logs that analysis scripts write themselves. In a regulated company, those logs often serve as evidence for an electronic record: the dataset, table, or figure the script produced. That changes how they are created, named, and archived.

Why regulated logs are different

Part 11 requires secure, computer generated, time stamped audit trails that record operator actions without obscuring earlier entries. It also requires that the audit trail be kept at least as long as the record it supports.1 Annex 11 adds that audit trails must be readable and regularly reviewed, and that archived data must stay accessible, readable, and intact.2

Regulators summarize these expectations as ALCOA+.3 The European Medicines Agency adds a tenth attribute, traceable, for clinical trial data.4 Each attribute turns into a concrete rule for a log file:

Attribute What the log needs
Attributable The user, host, and process ID in every run header
Legible Plain text in fixed columns that grep can search
Contemporaneous ISO 8601 timestamps in UTC, from a clock synced with NTP
Original Append only writes; nobody edits a log by hand
Accurate The code version, package versions, and input checksums
Complete The start, the end, the exit status, and every warning and error
Consistent The same format from R and Python
Enduring A checksum, compression, and retention set by SOP
Available An index that finds any log within minutes
Traceable A link from each output back to its inputs and code version

In short, a log must say who ran which version of the code, on which inputs, when, and with what result. It must then be kept in a way that proves nobody changed it. A reviewer has to be able to read it, too. A log that nobody reviews satisfies none of these attributes.

Creating log files

Use a logging framework

Use a logging framework instead of print() or cat(). A framework adds levels, timestamps, and several destinations to every message.

Python ships the logging module. R has no built in equivalent, but the {logger} package is modeled on Python's logging.5 Teams that use both languages keep one way of thinking about logs. {lgr} is an alternative when you need logger hierarchies or JSON appenders.8

Agree on log levels

The common levels, in priority order, are FATAL, ERROR, WARN, INFO, DEBUG, and TRACE.9 Define them in an SOP, so that WARN means the same thing in an R script and a Python script. The table below is one convention for GxP work:

Level Use for
FATAL The run cannot continue, and its output must not be used
ERROR A step failed, and its output is incomplete or invalid
WARN Something unexpected was handled (such as imputed values or a deprecated function); a reviewer must read it
INFO Milestones: start and end, inputs loaded, outputs written, row counts
DEBUG Parameters and intermediate values; off in production unless you are investigating

Posit's logging guidance suggests an easy first step. Many scripts already mark their sections with comments, and replacing those comments with INFO messages is a good start.9

Every log opens with a header that records who ran the script, where, and with what. It closes with an explicit status line. An inspector reads these two lines first.

The Python example below writes each run to its own file and to the console. Setting Formatter.converter to time.gmtime makes every timestamp UTC.10 Renaming WARNING and CRITICAL keeps the level column five characters wide and matches the R names.

import getpass, logging, os, socket, sys, time
from datetime import datetime, timezone
from pathlib import Path

script = Path(__file__).stem
run_ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
log_file = Path("/srv/gxp-logs", script, f"{run_ts}_{script}_{getpass.getuser()}_{socket.gethostname()}.log")
log_file.parent.mkdir(parents=True, exist_ok=True)

logging.Formatter.converter = time.gmtime
logging.addLevelName(logging.WARNING, "WARN")
logging.addLevelName(logging.CRITICAL, "FATAL")
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s.%(msecs)03dZ | %(levelname)-5s | %(name)s | %(message)s",
    datefmt="%Y-%m-%dT%H:%M:%S",
    handlers=[logging.FileHandler(log_file), logging.StreamHandler()],
)
log = logging.getLogger(script)

log.info("=== RUN START === user=%s pid=%d python=%s", getpass.getuser(), os.getpid(), sys.version.split()[0])
try:
    ...  # the analysis
    log.info("=== RUN END status=SUCCESS ===")
except Exception:
    log.exception("=== RUN END status=FAILED ===")
    raise

The R version below does the same with {logger}. appender_tee() writes to the file and the console at once.5 withCallingHandlers() logs each warning and then muffles it, so it is not printed a second time. tryCatch() logs the failure before stopping:

library(logger)

script   <- "adsl_derivation"
user     <- Sys.info()[["user"]]
run_ts   <- format(Sys.time(), "%Y%m%dT%H%M%SZ", tz = "UTC")
log_file <- file.path("/srv/gxp-logs", script,
  sprintf("%s_%s_%s_%s.log", run_ts, script, user, Sys.info()[["nodename"]]))
dir.create(dirname(log_file), recursive = TRUE, showWarnings = FALSE)

log_layout(layout_glue_generator(
  "{format(time, '%Y-%m-%dT%H:%M:%OS3Z', tz = 'UTC')} | {sprintf('%-5s', level)} | {ns} | {msg}"
))
log_appender(appender_tee(log_file))

log_info("=== RUN START === user={user} pid={Sys.getpid()} R={getRversion()}")
tryCatch(
  withCallingHandlers(
    {
      # the analysis
    },
    warning = function(w) {
      log_warn(conditionMessage(w))
      invokeRestart("muffleWarning")
    }
  ),
  error = function(e) {
    log_fatal("=== RUN END status=FAILED === {conditionMessage(e)}")
    stop(e)
  }
)
log_info("=== RUN END status=SUCCESS ===")

A real header holds more than these examples show. Add the Git revision of the code, the lock file's checksum (renv.lock or requirements.txt), and, for each input, its path, SHA-256 checksum, and row count.

When {logger} is called from inside an R package, it uses the package name as the namespace (the {ns} field).6 Each line then shows which internal package wrote it.

Logging from Bash scripts

Bash has no logging framework, but a short function writes the same line format as R and Python. The example below writes one file per run and sends each line to standard error. Standard output stays free for the data the script produces:

#!/bin/bash
#
# stage_data: copy the raw extract to staging, with a run log.

set -uo pipefail

SCRIPT="$(basename "$0")"
readonly SCRIPT
RUN_ID="$(date -u +%Y%m%dT%H%M%SZ)_${SCRIPT}_$(id -un)_$(hostname -s)"
readonly RUN_ID
readonly LOG_DIR="/srv/gxp-logs/${SCRIPT}"
readonly LOG_FILE="${LOG_DIR}/${RUN_ID}.log"

#######################################
# Write one line to the run log and to STDERR.
# Globals:
#   SCRIPT
#   LOG_FILE
# Arguments:
#   Level, then the message.
#######################################
log() {
  local level="$1"
  shift
  printf '%s | %-5s | %s | %s\n' \
    "$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)" "${level}" "${SCRIPT}" "$*" \
    | tee -a "${LOG_FILE}" >&2
}

#######################################
# Write the footer line.
# Arguments:
#   Exit status of the script.
#######################################
log_end() {
  local status='SUCCESS'
  (( $1 == 0 )) || status='FAILED'
  log INFO "=== RUN END status=${status} exit=$1 ==="
}

main() {
  local sum
  if ! mkdir -p "${LOG_DIR}"; then
    echo "${SCRIPT}: cannot create ${LOG_DIR}" >&2
    exit 1
  fi
  # The footer is written on every exit, including errors and early exits
  trap 'log_end $?' EXIT
  sum="$(sha256sum "$0" | cut -c1-12)"
  log INFO "=== RUN START === user=$(id -un) pid=$$ sha256=${sum}"

  if ! cp data/raw.csv data/stage.csv; then
    log ERROR "copy failed src=data/raw.csv"
    exit 1
  fi
}

main "$@"

A few rules apply to Bash in particular:

  • Footer: trap ... EXIT writes the status line however the script ends, so a run without one was killed.
  • Version: record a checksum of the script itself. Bash scripts on a server are often copies, so a Git revision may not exist.
  • Exit status: set -o pipefail keeps a failure visible when a command's output goes through | tee. Without it, the pipeline reports the status of tee.
  • Secrets: never leave set -x on in production. It prints every command after expansion, passwords included.
  • Colors: color output only when [[ -t 2 ]] is true, so the file never holds escape codes.
  • A second copy: logger -t "$SCRIPT" "message" sends a line to the system journal or syslog. This is the util-linux command, not the R package.

The admin scripts are reports, not logs, but they follow the same rules. Each report opens with the script's checksum, the host, the user, the PID, and a UTC start time. It ends with a UTC end time and the exit status, written by a trap, and colors appear only on a terminal.

Format lines for the terminal

Administrators read logs with less, grep, awk, and tail -f. For the file people read, use one line per event, with fields separated by pipes:

2026-11-04T14:03:22.117Z | INFO  | adsl_derivation | input file=raw/dm.sas7bdat sha256=9f3a... rows=412
2026-11-04T14:03:23.004Z | WARN  | adsl_derivation | 3 subjects missing RFSTDTC; imputed per SAP 4.2
2026-11-04T14:03:25.881Z | ERROR | adsl_derivation | merge key USUBJID not unique in ex.sas7bdat

A few rules keep these lines easy to search:

  • Timestamp first: ISO 8601 in UTC with the Z suffix sorts correctly, and grep '^2026-11-04T14' finds an hour. Sync every host's clock with NTP, and include that in the validation package.
  • Fixed width level: padding the level to five characters makes grep ' ERROR ' and awk -F'|' '$2 ~ /WARN|ERROR/' reliable.
  • key=value pairs: the message stays readable and can still be parsed. If a log aggregator needs JSON, write a second .jsonl file; {logger} provides layout_json() and formatter_json() for this.5
  • One event per line: indent stack traces, so grep -v '^\s' filters them out.
  • No color codes in the file: colors belong on the console only.

Leave things out

Some content never belongs in a log:

  • Subject data: log counts of USUBJID, not names, birth dates, or adverse event narratives.
  • Secrets: mask credentials, tokens, and connection strings.
  • Whole data frames: log the shape, the column names, and a checksum.

Configure logging in one place

Put the logging setup in one shared place, so every script writes the same format. In Python, that is a dictConfig() dictionary, which Python recommends for new applications.10 In R, it is a setup_logger() function in an internal package.

Libraries are the exception. A Python library should add only a NullHandler and leave handlers to the application.10 The same rule holds for R: a package defines its loggers, but the package user configures them.8

Naming log files

Use a fixed pattern

A naming convention is a schema that ls and cut can read. This pattern puts the timestamp first:

<YYYYMMDDTHHMMSSZ>_<system>_<job>_<user>_<host>[_<run id>].log

The files below follow it:

20261104T140322Z_cdw_adsl-derivation_jsmith_hpc-node07.log
20261104T140322Z_cdw_adsl-derivation_jsmith_hpc-node07.jsonl
20261104T140322Z_cdw_adsl-derivation_jsmith_hpc-node07.log.sha256
20261104T020000Z_lims_nightly-etl_svc-etl_etl-prod01_a81f3c.log

Each part has a job:

Part Why it is there
Timestamp (UTC, compact ISO 8601) ls sorts by time, and sites in different time zones agree
System ls /srv/gxp-logs/cdw finds one system's logs
Job Matches the script name and, where possible, the validated procedure ID
User Attributes the run to a named person or service account, never a shared login.1
Host Tells compute nodes apart, which matters when you reproduce a problem
Run ID (optional) A short ID or scheduler job ID, for when one script runs twice in the same second

Keep names simple

These rules let cut -d_ -f3 find the same part in every name:

  • Lowercase ASCII only, with - inside a part and _ between parts.
  • No spaces, no : (it breaks on Windows), and no . except before the extension.
  • Under about 100 characters.
  • .log for text, .jsonl for JSON lines, and .log.gz for compressed files.

Mirror the name in directories

Directories by system, job, year, and month keep any one folder small:

/srv/gxp-logs/
├── cdw/
│   └── adsl-derivation/
│       ├── 2026/
│       │   └── 11/
│       │       ├── 20261104T140322Z_cdw_adsl-derivation_jsmith_hpc-node07.log
│       │       └── 20261104T140322Z_cdw_adsl-derivation_jsmith_hpc-node07.log.sha256
│       └── current -> 2026/11/20261104T140322Z_cdw_adsl-derivation_jsmith_hpc-node07.log
└── lims/
    └── nightly-etl/

The current link gives tail -f a fixed path to the newest run.

One file per run

Analysis scripts should write one file per run, not one rolling app.log. One file maps to the one output it supports (a table, a dataset, a batch report), so the two can be archived together.

Rolling files belong to long running services such as Shiny apps and APIs. Python rotates them with RotatingFileHandler or TimedRotatingFileHandler, and {logger}'s appender_file() rotates with max_lines, max_bytes, and max_files.7

Where logs live on a Posit server

Logs need a location that outlives the session and the server's own cleanup. On Workbench, analysts cannot write to /var/log. Ask your sudo administrator to create a shared directory (/srv/gxp-logs in these examples), owned by a group that the analysts belong to.

Connect is different. It captures the standard output and error of every process it runs, and shows them in the content's Logs panel. That output lives in the jobs directory under the data directory, and Connect removes it after 30 days by default.11 Logging.ContentLog can also send content output to the service log or a file.12 Either way, a GxP log from a scheduled report needs its own file in a retained location, as above.

Archiving log files

The lifecycle

The diagram below follows one log from the run that writes it to its approved destruction. The retention tiers are examples; your SOP sets the real periods.

flowchart TD
    Run(["Script runs"]) --> Write("Append to the active directory")
    Write --> Close("Run ends: close the file<br/>and write a SHA-256 sidecar")
    Close --> Lock("Make it read only<br/>(chattr +i or a WORM share)")
    Lock --> Tier{"Age of the log"}
    Tier -->|"under 90 days"| Hot[("Hot: plain text on disk<br/>grep, less, tail")]
    Tier -->|"90 days to 2 years"| Warm[("Warm: gzip on the host or NAS<br/>zgrep, zless")]
    Tier -->|"2 years to the end<br/>of retention"| Cold[("Cold: archived with the record<br/>validated backup or object lock")]
    Hot --> Review("Periodic review,<br/>documented by QA")
    Warm --> Review
    Cold --> Expire("Retention ends per SOP")
    Expire --> Destroy(["Documented, approved destruction"])

    style Hot fill:#f1eaf6,stroke:#7a4f9a,stroke-width:2px,color:#1a1a1a
    style Warm fill:#f1eaf6,stroke:#7a4f9a,stroke-width:2px,color:#1a1a1a
    style Cold fill:#f1eaf6,stroke:#7a4f9a,stroke-width:2px,color:#1a1a1a

Make tampering detectable

Logs that support regulated records must be tamper evident as soon as the run ends. Part 11 requires that changes never obscure earlier entries.1 The steps below run from weakest to strongest:

  1. Append only writes: open the file in append mode, and never clean up a log by hand.
  2. A checksum sidecar: write <logfile>.sha256 when the run ends, and check it with sha256sum -c during review. Writing checksums to a separate manifest that the script's owner cannot change is stronger still.
  3. Immutable files: chmod 444 plus chattr +i, or a move to a WORM share or an object lock bucket. chattr +i needs root, so this step belongs to your sudo administrator, not the analyst.
  4. A second copy: forward each line to a central log server as it is written. Python has SysLogHandler, and {logger} has a syslog appender.5

Compress with gzip

Use gzip for the warm and cold tiers, because standard tools read it directly: zgrep, zless, and zcat | awk. One command searches a year of logs:

zgrep -h ' ERROR ' /srv/gxp-logs/cdw/adsl-derivation/2026/*/*.log.gz | sort

Compress each file on its own, not a month at a time in one tarball. Then a single run's log can be retrieved and checked without unpacking the rest. Keep the original .sha256, because it describes the uncompressed text. zcat file.log.gz | sha256sum should still match it.

Archive with the record

A log is kept as long as the record it supports.1 That has three consequences:

  • Archive together: when a dataset or table package is archived for a submission or batch release, its run logs go with it. A logs/ folder in the same bundle works well.
  • Retention follows the record: clinical data, batch records, and device design history files each have their own minimum. A log inherits the longest one that applies. Check that logrotate does not cover GxP log directories, or configure each one explicitly.
  • Keep the environment: store renv.lock, requirements.txt or pip freeze output, and any container image digest next to the logs. A log that cites git_rev=a81f3c helps only if that commit and its dependencies can be rebuilt.

Prove you can retrieve it

Inspectors test availability by asking for every record behind a result. Plan for that request:

  • Keep an index that maps each run ID to its script, inputs, outputs, log path, and checksum. A CSV file or a SQLite table is enough.
  • Write the retrieval procedure into an SOP, and test a restore from cold storage on a schedule.
  • Keep archives in plain text and gzip, which will still be readable in 15 years.

Reviewing logs

Annex 11 expects audit trails to be reviewed regularly.2 A short routine that runs from the terminal makes that review cheap. The loop below prints each run with its final status, and marks runs that never logged a clean end:

for f in /srv/gxp-logs/cdw/*/2026/11/*.log; do
  status=$(grep -o 'RUN END status=[A-Z]*' "$f" | tail -n 1)
  printf '%s\t%s\n' "$(basename "$f")" "${status:-INCOMPLETE}"
done | column -t

Record that each review happened: who ran it, when, and what it flagged. That record joins the audit trail too.

Checklist

Creating:

  • logging in Python, {logger} or {lgr} in R; no print() or cat()
  • Shared level definitions and one line format across both languages
  • A header with the user, host, PID, script, Git revision, and language and package versions
  • For each input: the path, a checksum, and row and column counts
  • A footer with status=SUCCESS or status=FAILED and the elapsed time
  • UTC ISO 8601 timestamps on hosts synced with NTP
  • Warnings and errors captured (withCallingHandlers() in R, logging.exception() in Python)
  • No subject data, credentials, or whole datasets

Naming:

  • <UTC timestamp>_<system>_<job>_<user>_<host>.log
  • Lowercase ASCII, _ between parts and - inside them
  • One file per run for scripts; rotation only for services
  • Directories by system, job, year, and month, with a current link

Archiving:

  • Append only during the run, with a checksum sidecar at the end
  • Read only once closed, with a second copy on a central log server
  • Each file gzipped on its own, so zgrep and zless work
  • Kept with its record, for the record's retention period
  • Indexed, with a retrieval procedure that has been tested
  • Reviewed on a schedule, with each review documented

Recap

A regulated log is evidence, so it has to identify the run, survive unchanged, and turn up on request. Write one plain text file per run, with a header, a footer, and UTC timestamps. Name it so that ls sorts it and cut can parse it. Then lock it, checksum it, and archive it with the record it supports, for as long as that record is kept.