Gitlab ci step logging
Logging convention for GitLab CI/CD step scripts (Python). Use when creating or modifying a GitLab CI step's main.py that needs logging. Applies to scripts under steps/*/main.py. Provides dual-handler logging: FileHandler (DEBUG) writes to {project_dir}/build/log/ for artifact retention, StreamHandler (INFO) outputs concise messages to console. Also handles saving debug data (JSON, etc.) to the log directory.From its SKILL.md
npx -y skills add wiqun/Jarvis-skills --skill gitlab-ci-step-loggingAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
One thing to look at
- 0 stars0 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
SKILL.md
4.4 KB, as published. Nobody here has run it
GitLab CI Step Logging
Convention
Every step's main.py uses Python logging with two handlers:
| Handler | Target | Level | Format |
|---|---|---|---|
| FileHandler | {project_dir}/build/log/{job_name}/{step_name}.log | DEBUG | %(asctime)s [%(levelname)s] %(message)s |
| StreamHandler | console (stdout) | INFO | %(message)s |
Passing CI_JOB_NAME_SLUG via step.yml
CI_JOB_NAME_SLUG is a GitLab job-level context variable. In step.yml, directly reference ${{ job.CI_JOB_NAME_SLUG }} in the exec command and pass it to the Python script via --job-name:
spec:
inputs:
# ... other inputs
exec:
command:
- uv
- run
- main.py
- --project-dir
- ${{ job.project_dir }}
- --job-name
- ${{ job.CI_JOB_NAME_SLUG }}
Setup Pattern
import logging
logger = logging.getLogger("step-name")
def setup_logging(project_dir, job_name):
log_dir = os.path.join(project_dir, "build", "log", job_name)
os.makedirs(log_dir, exist_ok=True)
log_file = os.path.join(log_dir, "step_name.log")
file_handler = logging.FileHandler(log_file, encoding='utf-8')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(message)s'))
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(logging.Formatter('%(message)s'))
logger.setLevel(logging.DEBUG)
logger.addHandler(file_handler)
logger.addHandler(console_handler)
main() Integration
- Parse args first (argparse), including
--job-name - Validate
project_direxists — useprint(..., file=sys.stderr)before logging is ready - Call
setup_logging(args.project_dir, args.job_name) - Use
logger.*for all subsequent output
def main():
parser = argparse.ArgumentParser(...)
parser.add_argument("--project-dir", required=True, ...)
parser.add_argument("--job-name", required=True, help="CI_JOB_NAME_SLUG for log directory")
args = parser.parse_args()
if not os.path.exists(args.project_dir):
print(f"项目目录不存在: {args.project_dir}", file=sys.stderr)
sys.exit(1)
setup_logging(args.project_dir, args.job_name)
# ... rest of logic uses logger
Log Level Guidelines
| Level | Use for | Example |
|---|---|---|
logger.debug() | API responses, per-item details, intermediate data, sensitive params (tokens, URLs) | logger.debug(f"API URL: {url}") |
logger.info() | Key milestones, summary stats, start/end of major phases | logger.info(f"找到 {count} 个包") |
logger.error() | Failures, exceptions, validation errors | logger.error(f"请求失败: HTTP {code}") |
Saving Debug Data
Save intermediate data (JSON, etc.) to the same build/log/{job_name}/ directory:
log_dir = os.path.join(project_dir, "build", "log", job_name)
data_path = os.path.join(log_dir, "data_name.json")
try:
with open(data_path, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
logger.debug(f"数据已保存到: {data_path}")
except OSError as e:
logger.debug(f"保存数据失败: {e}")
Artifact Retention
The consuming GitLab CI job must configure artifacts to retain log files:
artifacts:
name: log
paths:
- build/log/*.log
expire_in: 1 day
when: always
- If you are modifying the GitLab CI job (e.g.,
template.yml), add thisartifactsblock to the job definition. - If you are only modifying the step (
step.yml/main.py) without touching the job, remind the user that the job needs thisartifactsconfiguration.
Migrating from print()
Replace all print() calls:
- Detailed process info →
logger.debug() - Important milestones and summaries →
logger.info() - Error messages →
logger.error() - Pre-logging errors (before
setup_logging) →print(..., file=sys.stderr)