linux-sysprog · beginner · ~10 min

Decode a syslog priority value

Parse and validate a small bracketed integer prefix.

Challenge

Read the <PRI> prefix at the start of a syslog line and extract the severity level (the low 3 bits of the priority value).

Task

Implement int syslog_severity(const char *line) that returns the syslog severity, or -1 on malformed input.

Input

  • line: a syslog line that should begin with <PRI>, where PRI = facility * 8 + severity and is in the range 0–191.

Output

Returns the severity, computed as PRI % 8 (a value 0–7). Returns -1 if the line does not start with <, has no digits after <, has more than 3 digits, has no closing >, or has PRI > 191 (also -1 for a NULL line).

Example

syslog_severity("<34>Oct 11 host app")   ->   2     (34 % 8)
syslog_severity("<0>x")                   ->   0
syslog_severity("<191>x")                 ->   7
syslog_severity("34>x")                   ->   -1    (no '<')
syslog_severity("<>x")                    ->   -1    (no digits)
syslog_severity("<999>x")                 ->   -1    (PRI > 191)
syslog_severity("<12")                    ->   -1    (no closing '>')
syslog_severity(NULL)                     ->   -1

Edge cases

  • PRI 0 and 191 are the valid extremes.
  • More than 3 digits, a missing bracket, or NULL all return -1.

Why this matters

Every syslog line starts with <PRI>; severity = PRI mod 8. Triage pipelines read it constantly.

Input format

A syslog line beginning with , where PRI = facility*8 + severity (0-191). May be NULL.

Output format

The severity PRI % 8 (0-7), or -1 if the prefix is malformed or PRI > 191.

Constraints

Require a leading '<', 1-3 digits, a closing '>', and PRI <= 191; otherwise -1.

Starter code

int syslog_severity(const char *line) {
    /* TODO */
    (void)line;
    return -1;
}

Common mistakes

Forgetting the closing '>'. Allowing PRI > 191. Not capping digit count.

Edge cases to handle

PRI 0 and 191 (the extremes). Missing bracket. Overlong number.

Complexity

O(1).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.