Taskcore
Log an error
Also called log an exception, error logging, logging errors, log the error and continue.
Handle an error where it happens by writing one log record at the error level, with the context and the cause as escaped fields, and then go on with the next item.
- Evidence
- Code in 10 languages
Task
Some errors stop only one item of a job. A server that reads a list of settings can skip a bad setting and use the others. The program must not hide the error. The Python logging guide gives the tool for this case: to "Report suppression of an error without raising an exception", use "A logger’s error(), exception() or critical() method"1.
Write read_ports(texts, log). It reads each text as a TCP port number, with the parser of Wrap an error with context: the messages are "not a number: 'TEXT'" and "out of range: TEXT". It returns the good ports in order. For each bad text, it writes one log record at the error level, with the line number and the message of the error. At the end, it writes one record at the info level with the number of good ports and the number of texts. For example, read_ports(["8080", "x", "443"], log) returns [8080, 443] and writes:
level=ERROR msg="read port failed" line=2 err="not a number: 'x'"
level=INFO msg="ports read" ok=2 total=3
The records use the form of the text handler of Go's log/slog, without the time. Each field is key=value. A value is in double quotes when it has a space or a special character, and a backslash, a double quote, a line feed, a carriage return or a tab in it is escaped. Structured logging explains why fields are better than free text.
Solutions
| Language | The logger | The error level | The exception in the record |
|---|---|---|---|
| Python | logging.Logger2 |
log.error1 |
log.exception, or exc_info=True2 |
| JavaScript, TypeScript | a function, console.error by default3 |
console.error3 |
in the message |
| Java | java.util.logging.Logger4 |
Level.SEVERE5 |
log(Level, String, Throwable)4 |
| C# | a TextWriter; in an app, ILogger6 |
LogError6 |
an overload with an exception6 |
| Go | *slog.Logger7 |
Logger.Error7 |
an err attribute |
| Rust | an io::Write; in an app, the log crate8 |
error!8 |
in the message |
| C, C++ | a FILE *, a std::ostream |
in the text | in the message |
| Bash | the standard error | in the text | in the message |
Each solution takes the logger as a parameter, so that the test can read what it wrote. Each solution handles the error at one place: it logs the error and does not throw it or return it again.
- Python. The logging guide describes the level ERROR with the words "Due to a more serious problem, the software has not been able to perform some function"1.
make_loggergets the logger withlogging.getLogger, because "Loggers should NEVER be instantiated directly"2. Its formatter writeslevel=and the level name.read_portscallslog.errorwith%arguments, andquoteescapes the message. To add the traceback, calllog.exceptionin theexceptblock. "Exception info is added to the logging message. This method should only be called from an exception handler"2. - JavaScript and TypeScript. "The console.error() static method outputs a message to the console", at the error log level3.
readPortstakes a function that writes one line, andconsole.erroris the default. The test gives a function that keeps the lines in a string. - Java.
java.util.loggingnames its top levelSEVERE: "SEVERE is a message level indicating a serious failure"5. The solution callslog(Level level, String msg, Throwable thrown), which logs "a message, with associated Throwable information"4. So a handler can write the stack trace. The formatter of the solution writesERRORforSEVEREand does not write the stack trace, so that the output of the test is short. - C#. .NET apps log through
ILogger, from the NuGet packageMicrosoft.Extensions.Logging6. ItsLogErroris "For errors and exceptions that can't be handled", and "The logger methods have overloads that take an exception parameter"6. The solution writes to aTextWriter, so that it needs only the base library. It writes"\n"and notWriteLine, so that each line ends in the same way on each platform. - Go. "Package slog provides structured logging, in which log records include a message, a severity level, and various other attributes expressed as key-value pairs"7. The solution calls
log.Errorwith the message and the pairslineanderr, and gets such a record.NewLoggerremoves the time withReplaceAttr, as the examples of the package do7. The text handler does the escaping: "Keys and values are quoted with strconv.Quote if they contain Unicode space characters, non-printing characters"7. - Rust. The standard library has no logger. The log crate is "A lightweight logging facade", with "five logging macros: error!, warn!, info!, debug! and trace!"8. The solution writes to an
io::Writewithwriteln!, and gives an error of the writer to the caller. - C and C++. The solutions write the lines to a
FILE *or astd::ostream, with a function that escapes the message. The C test reads the lines back fromtmpfile(). - Bash.
read_portsprints the good ports on the standard output and the log lines on the standard error, so that a caller can pipe the ports to another command and still see the log.
The escape at work
The bad text here has a line feed and a double quote. The text handler of slog puts the value in quotes and escapes them, so the record stays on one line:
package main
import (
"fmt"
"log/slog"
"os"
)
func main() {
removeTime := func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey && len(groups) == 0 {
return slog.Attr{}
}
return a
}
log := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: removeTime}))
text := "80\nlevel=INFO msg=\"all good\""
err := fmt.Errorf("not a number: '%s'", text)
log.Error("read port failed", "line", 1, "err", err)
}
level=ERROR msg="read port failed" line=1 err="not a number: '80\nlevel=INFO msg=\"all good\"'"
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty-list: no texts. The log has only the summary, withok=0 total=0.empty-text: the message isnot a number: '', and the record still has a value in quotes.boundary: 1 and 65535 are good, and 0 is out of range.newline,backslash,carriage-returnandtab: each special character is escaped, so each record is one line.
Pitfalls
- Log and return. Dave Cheney writes: "you should only handle errors once. Handling an error means inspecting the error value, and making a decision"9. When each level logs the error and also returns it, the log gets the same error many times:
This code runs but gives a wrong answer on purpose.
package main
import (
"log"
"os"
"strconv"
)
func readPort(text string) (int, error) {
port, err := strconv.Atoi(text)
if err != nil {
log.Println("read port failed:", err)
return 0, err
}
return port, nil
}
func loadConfig(text string) error {
if _, err := readPort(text); err != nil {
log.Println("load config failed:", err)
return err
}
return nil
}
func main() {
log.SetFlags(0)
log.SetOutput(os.Stdout)
if err := loadConfig("x"); err != nil {
log.Println("error:", err)
}
}
read port failed: strconv.Atoi: parsing "x": invalid syntax
load config failed: strconv.Atoi: parsing "x": invalid syntax
error: strconv.Atoi: parsing "x": invalid syntax
Pick one: log the error and stop there, or wrap it and return it, as in Wrap an error with context. The level that handles it writes the log record.
- Log injection. The OWASP cheat sheet says: "Perform sanitization on all event data to prevent log injection attacks e.g. carriage return (CR), line feed (LF) and delimiter characters"10. Here the bad text goes into the record with no escape, and it makes a second record that looks real:
This code runs but gives a wrong answer on purpose.
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="level=%(levelname)s %(message)s")
log = logging.getLogger("ports")
text = '80\nlevel=INFO msg="all good"'
log.error("msg=\"read port failed\" line=1 err=not a number: '%s'", text)
level=ERROR msg="read port failed" line=1 err=not a number: '80
level=INFO msg="all good"'
The solutions put each value in quotes and escape it.
- Secrets in the log. An error message can hold the input that caused it. The OWASP cheat sheet lists data that "should usually not be recorded directly in the logs", such as "Session identification values", "Access tokens" and "Authentication passwords"10. Remove or mask such a value before it goes into the message.
- A level that the logger drops. In Python, "The default level is WARNING, which means that only events of this severity and higher will be tracked, unless the logging package is configured to do otherwise"1. Without
setLevel(logging.INFO), the summary record ofread_portsgoes nowhere.
Related tasks
- Wrap an error with context: add context to an error and return it, when this level cannot handle it.
- Define a custom error type: an error with fields, which a logger can write as fields.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/log-an-error/.
import logging
from typing import TextIO
def parse_port(text: str) -> int:
"""Return the port number in text, or raise ValueError."""
if text == "" or any(c not in "0123456789" for c in text):
raise ValueError(f"not a number: '{text}'")
port = int(text)
if not 1 <= port <= 65535:
raise ValueError(f"out of range: {text}")
return port
def quote(value: str) -> str:
"""Put value in double quotes and escape the characters that could end the line or the value."""
for c, e in (("\\", "\\\\"), ('"', '\\"'), ("\n", "\\n"), ("\r", "\\r"), ("\t", "\\t")):
value = value.replace(c, e)
return f'"{value}"'
def make_logger(name: str, stream: TextIO) -> logging.Logger:
"""Return the logger name, which writes INFO and higher to stream in the form level=LEVEL message."""
logger = logging.getLogger(name)
logger.handlers.clear()
handler = logging.StreamHandler(stream)
handler.setFormatter(logging.Formatter("level=%(levelname)s %(message)s"))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.propagate = False
return logger
def read_ports(texts: list[str], log: logging.Logger) -> list[int]:
"""Return the good ports. Log each bad text at the ERROR level, then a summary."""
ports = []
for line, text in enumerate(texts, start=1):
try:
ports.append(parse_port(text))
except ValueError as e:
# The error is handled here: it is logged once and not raised again.
log.error('msg="read port failed" line=%d err=%s', line, quote(str(e)))
log.info('msg="ports read" ok=%d total=%d', len(ports), len(texts))
return ports
test_read_ports.py 30 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/log-an-error/.
import io
import pytest
from read_ports import make_logger, read_ports
CASES = {
"one-bad": (["8080", "x", "443"], [8080, 443], "level=ERROR msg=\"read port failed\" line=2 err=\"not a number: 'x'\"\nlevel=INFO msg=\"ports read\" ok=2 total=3\n"),
"all-good": (["80", "443"], [80, 443], "level=INFO msg=\"ports read\" ok=2 total=2\n"),
"out-of-range": (["70000"], [], "level=ERROR msg=\"read port failed\" line=1 err=\"out of range: 70000\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"),
"empty-list": ([], [], "level=INFO msg=\"ports read\" ok=0 total=0\n"),
"empty-text": ([""], [], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: ''\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"),
"boundary": (["1", "65535", "0"], [1, 65535], "level=ERROR msg=\"read port failed\" line=3 err=\"out of range: 0\"\nlevel=INFO msg=\"ports read\" ok=2 total=3\n"),
"newline": (["80\nlevel=INFO msg=\"all good\""], [], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '80\\nlevel=INFO msg=\\\"all good\\\"'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"),
"backslash": (["C:\\port"], [], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: 'C:\\\\port'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"),
"carriage-return": (["80\r"], [], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '80\\r'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"),
"tab": (["8\t0"], [], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '8\\t0'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"),
}
@pytest.mark.parametrize("name", CASES)
def test_read_ports(name):
texts, want_ports, want_log = CASES[name]
stream = io.StringIO()
ports = read_ports(texts, make_logger("test_read_ports", stream))
assert ports == want_ports
assert stream.getvalue() == want_log
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/log-an-error/.
#include "read_ports.hpp"
#include <algorithm>
#include <stdexcept>
int parse_port(const std::string &text) {
if (text.empty() || !std::all_of(text.begin(), text.end(), [](char c) { return c >= '0' && c <= '9'; })) {
throw std::invalid_argument("not a number: '" + text + "'");
}
long value = 0;
for (char c : text) {
value = value * 10 + (c - '0');
if (value > 65535) {
throw std::out_of_range("out of range: " + text);
}
}
if (value == 0) {
throw std::out_of_range("out of range: " + text);
}
return static_cast<int>(value);
}
std::string quote(const std::string &value) {
std::string s = "\"";
for (char c : value) {
switch (c) {
case '\\': s += "\\\\"; break;
case '"': s += "\\\""; break;
case '\n': s += "\\n"; break;
case '\r': s += "\\r"; break;
case '\t': s += "\\t"; break;
default: s += c;
}
}
return s + "\"";
}
std::vector<int> read_ports(const std::vector<std::string> &texts, std::ostream &log) {
std::vector<int> ports;
for (std::size_t i = 0; i < texts.size(); i++) {
try {
ports.push_back(parse_port(texts[i]));
} catch (const std::logic_error &e) {
// The error is handled here: it is logged once and not thrown again.
log << "level=ERROR msg=\"read port failed\" line=" << i + 1 << " err=" << quote(e.what()) << "\n";
}
}
log << "level=INFO msg=\"ports read\" ok=" << ports.size() << " total=" << texts.size() << "\n";
return ports;
}
read_ports.hpp 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/log-an-error/.
#pragma once
#include <ostream>
#include <string>
#include <vector>
// parse_port returns the port number in text. It throws std::invalid_argument
// or std::out_of_range.
int parse_port(const std::string &text);
// quote puts value in double quotes and escapes the characters that could end
// the line or the value.
std::string quote(const std::string &value);
// read_ports returns the good ports. It writes a log line to log for each bad
// text, then a summary.
std::vector<int> read_ports(const std::vector<std::string> &texts, std::ostream &log);
test_read_ports.cpp 40 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/log-an-error/.
#include "read_ports.hpp"
#include <iostream>
#include <sstream>
#include <string>
#include <string_view>
#include <vector>
static int failures = 0;
static void check(std::string_view name, const std::vector<std::string> &texts, const std::vector<int> &want_ports,
const std::string &want_log) {
std::ostringstream log;
std::vector<int> ports = read_ports(texts, log);
if (ports != want_ports || log.str() != want_log) {
std::cerr << "case " << name << " failed: log " << log.str() << "\n";
failures++;
}
}
int main() {
check("one-bad", {"8080", "x", "443"}, {8080, 443}, "level=ERROR msg=\"read port failed\" line=2 err=\"not a number: 'x'\"\nlevel=INFO msg=\"ports read\" ok=2 total=3\n");
check("all-good", {"80", "443"}, {80, 443}, "level=INFO msg=\"ports read\" ok=2 total=2\n");
check("out-of-range", {"70000"}, {}, "level=ERROR msg=\"read port failed\" line=1 err=\"out of range: 70000\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n");
check("empty-list", {}, {}, "level=INFO msg=\"ports read\" ok=0 total=0\n");
check("empty-text", {""}, {}, "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: ''\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n");
check("boundary", {"1", "65535", "0"}, {1, 65535}, "level=ERROR msg=\"read port failed\" line=3 err=\"out of range: 0\"\nlevel=INFO msg=\"ports read\" ok=2 total=3\n");
check("newline", {"80\nlevel=INFO msg=\"all good\""}, {}, "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '80\\nlevel=INFO msg=\\\"all good\\\"'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n");
check("backslash", {"C:\\port"}, {}, "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: 'C:\\\\port'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n");
check("carriage-return", {"80\r"}, {}, "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '80\\r'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n");
check("tab", {"8\t0"}, {}, "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '8\\t0'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n");
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/log-an-error/.
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/** Reads port settings and logs the bad ones with java.util.logging. */
final class ReadPorts {
private ReadPorts() {}
/** Returns the port number in text, or throws IllegalArgumentException. */
static int parsePort(String text) {
if (text.isEmpty() || !text.chars().allMatch(c -> c >= '0' && c <= '9')) {
throw new IllegalArgumentException("not a number: '" + text + "'");
}
int port = 0;
for (int i = 0; i < text.length(); i++) {
port = port * 10 + (text.charAt(i) - '0');
if (port > 65535) {
throw new IllegalArgumentException("out of range: " + text);
}
}
if (port == 0) {
throw new IllegalArgumentException("out of range: " + text);
}
return port;
}
/** Puts value in double quotes and escapes the characters that could end the line or the value. */
static String quote(String value) {
StringBuilder sb = new StringBuilder("\"");
for (char c : value.toCharArray()) {
switch (c) {
case '\\' -> sb.append("\\\\");
case '"' -> sb.append("\\\"");
case '\n' -> sb.append("\\n");
case '\r' -> sb.append("\\r");
case '\t' -> sb.append("\\t");
default -> sb.append(c);
}
}
return sb.append('"').toString();
}
/**
* Writes level=LEVEL and the message. SEVERE is written as ERROR. This formatter does not write
* the Throwable of the record, so that the test output is short; a real formatter writes its stack
* trace.
*/
static final class LogfmtFormatter extends Formatter {
@Override
public String format(LogRecord r) {
String level = r.getLevel() == Level.SEVERE ? "ERROR" : r.getLevel().getName();
return "level=" + level + " " + r.getMessage() + "\n";
}
}
/** A handler that keeps the formatted records in a string. */
static final class StringHandler extends Handler {
private final StringBuilder text = new StringBuilder();
private final Formatter formatter = new LogfmtFormatter();
@Override
public void publish(LogRecord r) {
if (isLoggable(r)) {
text.append(formatter.format(r));
}
}
@Override
public void flush() {}
@Override
public void close() {}
String text() {
return text.toString();
}
}
/** Returns the good ports. Logs each bad text at the SEVERE level with its exception, then a summary. */
static List<Integer> readPorts(List<String> texts, Logger log) {
List<Integer> ports = new ArrayList<>();
for (int i = 0; i < texts.size(); i++) {
try {
ports.add(parsePort(texts.get(i)));
} catch (IllegalArgumentException e) {
// The error is handled here: it is logged once and not thrown again.
log.log(Level.SEVERE, "msg=\"read port failed\" line=" + (i + 1) + " err=" + quote(e.getMessage()), e);
}
}
log.info("msg=\"ports read\" ok=" + ports.size() + " total=" + texts.size());
return ports;
}
}
ReadPortsTest.java 40 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/log-an-error/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class ReadPortsTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("one-bad", List.of("8080", "x", "443"), List.of(8080, 443), "level=ERROR msg=\"read port failed\" line=2 err=\"not a number: 'x'\"\nlevel=INFO msg=\"ports read\" ok=2 total=3\n"),
Arguments.of("all-good", List.of("80", "443"), List.of(80, 443), "level=INFO msg=\"ports read\" ok=2 total=2\n"),
Arguments.of("out-of-range", List.of("70000"), List.of(), "level=ERROR msg=\"read port failed\" line=1 err=\"out of range: 70000\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"),
Arguments.of("empty-list", List.of(), List.of(), "level=INFO msg=\"ports read\" ok=0 total=0\n"),
Arguments.of("empty-text", List.of(""), List.of(), "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: ''\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"),
Arguments.of("boundary", List.of("1", "65535", "0"), List.of(1, 65535), "level=ERROR msg=\"read port failed\" line=3 err=\"out of range: 0\"\nlevel=INFO msg=\"ports read\" ok=2 total=3\n"),
Arguments.of("newline", List.of("80\nlevel=INFO msg=\"all good\""), List.of(), "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '80\\nlevel=INFO msg=\\\"all good\\\"'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"),
Arguments.of("backslash", List.of("C:\\port"), List.of(), "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: 'C:\\\\port'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"),
Arguments.of("carriage-return", List.of("80\r"), List.of(), "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '80\\r'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"),
Arguments.of("tab", List.of("8\t0"), List.of(), "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '8\\t0'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void readPorts(String name, List<String> texts, List<Integer> wantPorts, String wantLog) {
Logger log = Logger.getAnonymousLogger();
log.setUseParentHandlers(false);
log.setLevel(Level.INFO);
ReadPorts.StringHandler handler = new ReadPorts.StringHandler();
log.addHandler(handler);
assertEquals(wantPorts, ReadPorts.readPorts(texts, log), name);
assertEquals(wantLog, handler.text(), name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/log-an-error/.
#include "read_ports.h"
int parse_port(const char *text, int *port, char *message, size_t size) {
int digits = text[0] != '\0';
for (const char *p = text; *p != '\0'; p++) {
if (*p < '0' || *p > '9') {
digits = 0;
}
}
if (!digits) {
snprintf(message, size, "not a number: '%s'", text);
return 1;
}
long value = 0;
for (const char *p = text; *p != '\0'; p++) {
value = value * 10 + (*p - '0');
if (value > 65535) {
break;
}
}
if (value == 0 || value > 65535) {
snprintf(message, size, "out of range: %s", text);
return 2;
}
*port = (int)value;
return 0;
}
void write_quoted(FILE *f, const char *value) {
fputc('"', f);
for (const char *p = value; *p != '\0'; p++) {
switch (*p) {
case '\\': fputs("\\\\", f); break;
case '"': fputs("\\\"", f); break;
case '\n': fputs("\\n", f); break;
case '\r': fputs("\\r", f); break;
case '\t': fputs("\\t", f); break;
default: fputc(*p, f);
}
}
fputc('"', f);
}
size_t read_ports(const char *const texts[], size_t n, int ports[], FILE *log) {
size_t ok = 0;
char message[256];
for (size_t i = 0; i < n; i++) {
int port;
if (parse_port(texts[i], &port, message, sizeof message) != 0) {
// The error is handled here: it is logged once and not returned.
fprintf(log, "level=ERROR msg=\"read port failed\" line=%zu err=", i + 1);
write_quoted(log, message);
fputc('\n', log);
continue;
}
ports[ok++] = port;
}
fprintf(log, "level=INFO msg=\"ports read\" ok=%zu total=%zu\n", ok, n);
return ok;
}
read_ports.h 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/log-an-error/.
#ifndef READ_PORTS_H
#define READ_PORTS_H
#include <stddef.h>
#include <stdio.h>
// parse_port stores the port number of text in *port and returns 0. On an
// error, it writes the message to message, which has room for size bytes,
// and returns 1 for a text that is not a number or 2 for a value out of range.
int parse_port(const char *text, int *port, char *message, size_t size);
// write_quoted writes value to f in double quotes, and escapes the characters
// that could end the line or the value.
void write_quoted(FILE *f, const char *value);
// read_ports reads the n texts, stores the good ports in ports, which has
// room for n values, and returns their number. It writes a log line to log
// for each bad text, then a summary.
size_t read_ports(const char *const texts[], size_t n, int ports[], FILE *log);
#endif
test_read_ports.c 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/log-an-error/.
#include "read_ports.h"
#include <string.h>
static int failures = 0;
static void check(const char *name, const char *const texts[], size_t n, const int want_ports[], size_t want_n,
const char *want_log) {
int ports[8];
char log[1024];
FILE *f = tmpfile();
if (f == NULL) {
fprintf(stderr, "case %s failed: no temporary file\n", name);
failures++;
return;
}
size_t got_n = read_ports(texts, n, ports, f);
rewind(f);
size_t len = fread(log, 1, sizeof log - 1, f);
log[len] = '\0';
fclose(f);
int same = got_n == want_n && strcmp(log, want_log) == 0;
for (size_t i = 0; same && i < got_n; i++) {
same = ports[i] == want_ports[i];
}
if (!same) {
fprintf(stderr, "case %s failed: log %s\n", name, log);
failures++;
}
}
int main(void) {
check("one-bad", (const char *const[]){"8080", "x", "443"}, 3, (const int[]){8080, 443}, 2, "level=ERROR msg=\"read port failed\" line=2 err=\"not a number: 'x'\"\nlevel=INFO msg=\"ports read\" ok=2 total=3\n");
check("all-good", (const char *const[]){"80", "443"}, 2, (const int[]){80, 443}, 2, "level=INFO msg=\"ports read\" ok=2 total=2\n");
check("out-of-range", (const char *const[]){"70000"}, 1, (const int[]){0}, 0, "level=ERROR msg=\"read port failed\" line=1 err=\"out of range: 70000\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n");
check("empty-list", (const char *const[]){NULL}, 0, (const int[]){0}, 0, "level=INFO msg=\"ports read\" ok=0 total=0\n");
check("empty-text", (const char *const[]){""}, 1, (const int[]){0}, 0, "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: ''\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n");
check("boundary", (const char *const[]){"1", "65535", "0"}, 3, (const int[]){1, 65535}, 2, "level=ERROR msg=\"read port failed\" line=3 err=\"out of range: 0\"\nlevel=INFO msg=\"ports read\" ok=2 total=3\n");
check("newline", (const char *const[]){"80\nlevel=INFO msg=\"all good\""}, 1, (const int[]){0}, 0, "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '80\\nlevel=INFO msg=\\\"all good\\\"'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n");
check("backslash", (const char *const[]){"C:\\port"}, 1, (const int[]){0}, 0, "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: 'C:\\\\port'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n");
check("carriage-return", (const char *const[]){"80\r"}, 1, (const int[]){0}, 0, "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '80\\r'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n");
check("tab", (const char *const[]){"8\t0"}, 1, (const int[]){0}, 0, "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '8\\t0'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n");
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/log-an-error/.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
/// <summary>Reads port settings and logs the bad ones.</summary>
public static class PortReader
{
/// <summary>Returns the port number in text, or throws FormatException.</summary>
public static int ParsePort(string text)
{
if (text.Length == 0)
{
throw new FormatException($"not a number: '{text}'");
}
foreach (char c in text)
{
if (c < '0' || c > '9')
{
throw new FormatException($"not a number: '{text}'");
}
}
int port = 0;
foreach (char c in text)
{
port = port * 10 + (c - '0');
if (port > 65535)
{
throw new FormatException($"out of range: {text}");
}
}
if (port == 0)
{
throw new FormatException($"out of range: {text}");
}
return port;
}
/// <summary>Puts value in double quotes and escapes the characters that could end the line or the value.</summary>
public static string Quote(string value)
{
var sb = new StringBuilder("\"");
foreach (char c in value)
{
sb.Append(c switch
{
'\\' => "\\\\",
'"' => "\\\"",
'\n' => "\\n",
'\r' => "\\r",
'\t' => "\\t",
_ => c.ToString(),
});
}
return sb.Append('"').ToString();
}
/// <summary>
/// Returns the good ports. Writes a log line to log for each bad text, then a summary.
/// Each line ends with "\n" on each platform.
/// </summary>
public static List<int> ReadPorts(IReadOnlyList<string> texts, TextWriter log)
{
var ports = new List<int>();
for (int i = 0; i < texts.Count; i++)
{
try
{
ports.Add(ParsePort(texts[i]));
}
catch (FormatException e)
{
// The error is handled here: it is logged once and not thrown again.
log.Write($"level=ERROR msg=\"read port failed\" line={i + 1} err={Quote(e.Message)}\n");
}
}
log.Write($"level=INFO msg=\"ports read\" ok={ports.Count} total={texts.Count}\n");
return ports;
}
}
ReadPortsTests.cs 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/log-an-error/.
using System.IO;
using Xunit;
public sealed class ReadPortsTests
{
public static TheoryData<string, string[], int[], string> Cases => new()
{
{ "one-bad", new string[] { "8080", "x", "443" }, new int[] { 8080, 443 }, "level=ERROR msg=\"read port failed\" line=2 err=\"not a number: 'x'\"\nlevel=INFO msg=\"ports read\" ok=2 total=3\n" },
{ "all-good", new string[] { "80", "443" }, new int[] { 80, 443 }, "level=INFO msg=\"ports read\" ok=2 total=2\n" },
{ "out-of-range", new string[] { "70000" }, new int[0], "level=ERROR msg=\"read port failed\" line=1 err=\"out of range: 70000\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n" },
{ "empty-list", new string[0], new int[0], "level=INFO msg=\"ports read\" ok=0 total=0\n" },
{ "empty-text", new string[] { "" }, new int[0], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: ''\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n" },
{ "boundary", new string[] { "1", "65535", "0" }, new int[] { 1, 65535 }, "level=ERROR msg=\"read port failed\" line=3 err=\"out of range: 0\"\nlevel=INFO msg=\"ports read\" ok=2 total=3\n" },
{ "newline", new string[] { "80\nlevel=INFO msg=\"all good\"" }, new int[0], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '80\\nlevel=INFO msg=\\\"all good\\\"'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n" },
{ "backslash", new string[] { "C:\\port" }, new int[0], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: 'C:\\\\port'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n" },
{ "carriage-return", new string[] { "80\r" }, new int[0], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '80\\r'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n" },
{ "tab", new string[] { "8\t0" }, new int[0], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '8\\t0'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n" },
};
[Theory]
[MemberData(nameof(Cases))]
public void Read(string name, string[] texts, int[] wantPorts, string wantLog)
{
Assert.NotNull(name);
var log = new StringWriter();
Assert.Equal(wantPorts, PortReader.ReadPorts(texts, log));
Assert.Equal(wantLog, log.ToString());
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/log-an-error/.
/**
* Returns the port number in text, or throws an Error.
* @param {string} text
* @returns {number}
*/
export function parsePort(text) {
if (!/^[0-9]+$/.test(text)) {
throw new Error(`not a number: '${text}'`);
}
const port = Number(text);
if (port < 1 || port > 65535) {
throw new Error(`out of range: ${text}`);
}
return port;
}
/**
* Puts value in double quotes and escapes the characters that could end the line or the value.
* @param {string} value
* @returns {string}
*/
export function quote(value) {
const escapes = { "\\": "\\\\", '"': '\\"', "\n": "\\n", "\r": "\\r", "\t": "\\t" };
return `"${value.replace(/[\\"\n\r\t]/g, (c) => escapes[c])}"`;
}
/**
* Returns the good ports. Writes a log line for each bad text, then a summary.
* The default log writer is console.error, which writes to the standard error stream.
* @param {string[]} texts
* @param {(line: string) => void} [log]
* @returns {number[]}
*/
export function readPorts(
texts,
log = (line) => console.error(line),
) {
const ports = [];
texts.forEach((text, i) => {
try {
ports.push(parsePort(text));
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
log(`level=ERROR msg="read port failed" line=${i + 1} err=${quote(message)}`);
}
});
log(`level=INFO msg="ports read" ok=${ports.length} total=${texts.length}`);
return ports;
}
readPorts.test.js 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/log-an-error/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { readPorts } from "./readPorts.js";
const cases = [
["one-bad", ["8080", "x", "443"], [8080, 443], "level=ERROR msg=\"read port failed\" line=2 err=\"not a number: 'x'\"\nlevel=INFO msg=\"ports read\" ok=2 total=3\n"],
["all-good", ["80", "443"], [80, 443], "level=INFO msg=\"ports read\" ok=2 total=2\n"],
["out-of-range", ["70000"], [], "level=ERROR msg=\"read port failed\" line=1 err=\"out of range: 70000\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"],
["empty-list", [], [], "level=INFO msg=\"ports read\" ok=0 total=0\n"],
["empty-text", [""], [], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: ''\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"],
["boundary", ["1", "65535", "0"], [1, 65535], "level=ERROR msg=\"read port failed\" line=3 err=\"out of range: 0\"\nlevel=INFO msg=\"ports read\" ok=2 total=3\n"],
["newline", ["80\nlevel=INFO msg=\"all good\""], [], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '80\\nlevel=INFO msg=\\\"all good\\\"'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"],
["backslash", ["C:\\port"], [], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: 'C:\\\\port'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"],
["carriage-return", ["80\r"], [], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '80\\r'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"],
["tab", ["8\t0"], [], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '8\\t0'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"],
];
for (const [name, texts, wantPorts, wantLog] of cases) {
test(name, () => {
let log = "";
const ports = readPorts(texts, (line) => {
log += line + "\n";
});
assert.deepEqual(ports, wantPorts);
assert.equal(log, wantLog);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/log-an-error/.
/** Returns the port number in text, or throws an Error. */
export function parsePort(text: string): number {
if (!/^[0-9]+$/.test(text)) {
throw new Error(`not a number: '${text}'`);
}
const port = Number(text);
if (port < 1 || port > 65535) {
throw new Error(`out of range: ${text}`);
}
return port;
}
/** Puts value in double quotes and escapes the characters that could end the line or the value. */
export function quote(value: string): string {
const escapes: Record<string, string> = { "\\": "\\\\", '"': '\\"', "\n": "\\n", "\r": "\\r", "\t": "\\t" };
return `"${value.replace(/[\\"\n\r\t]/g, (c) => escapes[c])}"`;
}
/**
* Returns the good ports. Writes a log line for each bad text, then a summary.
* The default log writer is console.error, which writes to the standard error stream.
*/
export function readPorts(
texts: string[],
log: (line: string) => void = (line) => console.error(line),
): number[] {
const ports: number[] = [];
texts.forEach((text, i) => {
try {
ports.push(parsePort(text));
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
log(`level=ERROR msg="read port failed" line=${i + 1} err=${quote(message)}`);
}
});
log(`level=INFO msg="ports read" ok=${ports.length} total=${texts.length}`);
return ports;
}
readPorts.test.ts 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/log-an-error/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { readPorts } from "./readPorts.ts";
const cases: [string, string[], number[], string][] = [
["one-bad", ["8080", "x", "443"], [8080, 443], "level=ERROR msg=\"read port failed\" line=2 err=\"not a number: 'x'\"\nlevel=INFO msg=\"ports read\" ok=2 total=3\n"],
["all-good", ["80", "443"], [80, 443], "level=INFO msg=\"ports read\" ok=2 total=2\n"],
["out-of-range", ["70000"], [], "level=ERROR msg=\"read port failed\" line=1 err=\"out of range: 70000\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"],
["empty-list", [], [], "level=INFO msg=\"ports read\" ok=0 total=0\n"],
["empty-text", [""], [], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: ''\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"],
["boundary", ["1", "65535", "0"], [1, 65535], "level=ERROR msg=\"read port failed\" line=3 err=\"out of range: 0\"\nlevel=INFO msg=\"ports read\" ok=2 total=3\n"],
["newline", ["80\nlevel=INFO msg=\"all good\""], [], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '80\\nlevel=INFO msg=\\\"all good\\\"'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"],
["backslash", ["C:\\port"], [], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: 'C:\\\\port'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"],
["carriage-return", ["80\r"], [], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '80\\r'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"],
["tab", ["8\t0"], [], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '8\\t0'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"],
];
for (const [name, texts, wantPorts, wantLog] of cases) {
test(name, () => {
let log = "";
const ports = readPorts(texts, (line) => {
log += line + "\n";
});
assert.deepEqual(ports, wantPorts);
assert.equal(log, wantLog);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/log-an-error/.
// Package ports reads port settings and logs the bad ones with log/slog.
package ports
import (
"errors"
"fmt"
"io"
"log/slog"
)
// The errors of ParsePort wrap one of these two values.
var (
ErrNotANumber = errors.New("not a number")
ErrOutOfRange = errors.New("out of range")
)
// ParsePort returns the port number in text.
func ParsePort(text string) (int, error) {
if text == "" {
return 0, fmt.Errorf("%w: '%s'", ErrNotANumber, text)
}
for _, c := range text {
if c < '0' || c > '9' {
return 0, fmt.Errorf("%w: '%s'", ErrNotANumber, text)
}
}
port := 0
for _, c := range text {
port = port*10 + int(c-'0')
if port > 65535 {
return 0, fmt.Errorf("%w: %s", ErrOutOfRange, text)
}
}
if port == 0 {
return 0, fmt.Errorf("%w: %s", ErrOutOfRange, text)
}
return port, nil
}
// NewLogger returns a logger that writes logfmt lines to w, without the
// time, so that the output is the same on each run.
func NewLogger(w io.Writer) *slog.Logger {
removeTime := func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey && len(groups) == 0 {
return slog.Attr{}
}
return a
}
return slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{ReplaceAttr: removeTime}))
}
// ReadPorts returns the good ports. It logs each bad text at the error
// level, then a summary at the info level. The text handler puts a value
// in quotes and escapes it when it has a space or a control character.
func ReadPorts(texts []string, log *slog.Logger) []int {
ports := make([]int, 0, len(texts))
for i, text := range texts {
port, err := ParsePort(text)
if err != nil {
// The error is handled here: it is logged once and not returned.
log.Error("read port failed", "line", i+1, "err", err)
continue
}
ports = append(ports, port)
}
log.Info("ports read", "ok", len(ports), "total", len(texts))
return ports
}
read_ports_test.go 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/log-an-error/.
package ports
import (
"slices"
"strings"
"testing"
)
var cases = []struct {
name string
texts []string
ports []int
log string
}{
{"one-bad", []string{"8080", "x", "443"}, []int{8080, 443}, "level=ERROR msg=\"read port failed\" line=2 err=\"not a number: 'x'\"\nlevel=INFO msg=\"ports read\" ok=2 total=3\n"},
{"all-good", []string{"80", "443"}, []int{80, 443}, "level=INFO msg=\"ports read\" ok=2 total=2\n"},
{"out-of-range", []string{"70000"}, []int{}, "level=ERROR msg=\"read port failed\" line=1 err=\"out of range: 70000\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"},
{"empty-list", []string{}, []int{}, "level=INFO msg=\"ports read\" ok=0 total=0\n"},
{"empty-text", []string{""}, []int{}, "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: ''\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"},
{"boundary", []string{"1", "65535", "0"}, []int{1, 65535}, "level=ERROR msg=\"read port failed\" line=3 err=\"out of range: 0\"\nlevel=INFO msg=\"ports read\" ok=2 total=3\n"},
{"newline", []string{"80\nlevel=INFO msg=\"all good\""}, []int{}, "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '80\\nlevel=INFO msg=\\\"all good\\\"'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"},
{"backslash", []string{"C:\\port"}, []int{}, "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: 'C:\\\\port'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"},
{"carriage-return", []string{"80\r"}, []int{}, "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '80\\r'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"},
{"tab", []string{"8\t0"}, []int{}, "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '8\\t0'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"},
}
func TestReadPorts(t *testing.T) {
for _, c := range cases {
var log strings.Builder
ports := ReadPorts(c.texts, NewLogger(&log))
if !slices.Equal(ports, c.ports) {
t.Errorf("%s: ports %v, want %v", c.name, ports, c.ports)
}
if log.String() != c.log {
t.Errorf("%s: log %q, want %q", c.name, log.String(), c.log)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/log-an-error/.
use std::io::{self, Write};
/// Returns the port number in text, or the message of the error.
pub fn parse_port(text: &str) -> Result<u16, String> {
if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
return Err(format!("not a number: '{text}'"));
}
let mut port: u32 = 0;
for b in text.bytes() {
port = port * 10 + u32::from(b - b'0');
if port > 65535 {
return Err(format!("out of range: {text}"));
}
}
if port == 0 {
return Err(format!("out of range: {text}"));
}
Ok(port as u16)
}
/// Puts value in double quotes and escapes the characters that could end
/// the line or the value.
pub fn quote(value: &str) -> String {
let mut s = String::from("\"");
for c in value.chars() {
match c {
'\\' => s.push_str("\\\\"),
'"' => s.push_str("\\\""),
'\n' => s.push_str("\\n"),
'\r' => s.push_str("\\r"),
'\t' => s.push_str("\\t"),
_ => s.push(c),
}
}
s.push('"');
s
}
/// Returns the good ports. Writes a log line to log for each bad text, then
/// a summary. An error of the writer goes to the caller.
pub fn read_ports(texts: &[&str], log: &mut dyn Write) -> io::Result<Vec<u16>> {
let mut ports = Vec::new();
for (i, text) in texts.iter().enumerate() {
match parse_port(text) {
Ok(port) => ports.push(port),
Err(e) => writeln!(log, "level=ERROR msg=\"read port failed\" line={} err={}", i + 1, quote(&e))?,
}
}
writeln!(log, "level=INFO msg=\"ports read\" ok={} total={}", ports.len(), texts.len())?;
Ok(ports)
}
tests/read_ports_test.rs 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/log-an-error/.
use algo_log_an_error::read_ports;
#[test]
fn cases() {
let cases: &[(&str, &[&str], &[u16], &str)] = &[
("one-bad", &["8080", "x", "443"], &[8080, 443], "level=ERROR msg=\"read port failed\" line=2 err=\"not a number: 'x'\"\nlevel=INFO msg=\"ports read\" ok=2 total=3\n"),
("all-good", &["80", "443"], &[80, 443], "level=INFO msg=\"ports read\" ok=2 total=2\n"),
("out-of-range", &["70000"], &[], "level=ERROR msg=\"read port failed\" line=1 err=\"out of range: 70000\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"),
("empty-list", &[], &[], "level=INFO msg=\"ports read\" ok=0 total=0\n"),
("empty-text", &[""], &[], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: ''\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"),
("boundary", &["1", "65535", "0"], &[1, 65535], "level=ERROR msg=\"read port failed\" line=3 err=\"out of range: 0\"\nlevel=INFO msg=\"ports read\" ok=2 total=3\n"),
("newline", &["80\nlevel=INFO msg=\"all good\""], &[], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '80\\nlevel=INFO msg=\\\"all good\\\"'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"),
("backslash", &["C:\\port"], &[], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: 'C:\\\\port'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"),
("carriage-return", &["80\r"], &[], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '80\\r'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"),
("tab", &["8\t0"], &[], "level=ERROR msg=\"read port failed\" line=1 err=\"not a number: '8\\t0'\"\nlevel=INFO msg=\"ports read\" ok=0 total=1\n"),
];
for &(name, texts, want_ports, want_log) in cases {
let mut log = Vec::new();
let ports = read_ports(texts, &mut log).unwrap();
assert_eq!(ports, want_ports, "{name}");
assert_eq!(String::from_utf8(log).unwrap(), want_log, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/log-an-error/.
# read_ports prints the good ports on the standard output, one on each line,
# and writes the log lines on the standard error.
# parse_port TEXT
# Sets PORT and returns 0, or sets ERROR_MESSAGE and returns 1 or 2.
parse_port() {
local text=$1 value=0 i
if [[ ! $text =~ ^[0-9]+$ ]]; then
ERROR_MESSAGE="not a number: '$text'"
return 1
fi
for ((i = 0; i < ${#text}; i++)); do
value=$((value * 10 + ${text:i:1}))
if ((value > 65535)); then
break
fi
done
if ((value == 0 || value > 65535)); then
ERROR_MESSAGE="out of range: $text"
return 2
fi
PORT=$value
}
# quote VALUE
# Prints VALUE in double quotes, and escapes the characters that could end
# the line or the value.
quote() {
local s=$1
s=${s//'\'/'\\'}
s=${s//'"'/'\"'}
s=${s//$'\n'/'\n'}
s=${s//$'\r'/'\r'}
s=${s//$'\t'/'\t'}
printf '"%s"' "$s"
}
# read_ports TEXT...
read_ports() {
local line=0 ok=0 text
for text in "$@"; do
line=$((line + 1))
if parse_port "$text"; then
echo "$PORT"
ok=$((ok + 1))
else
# The error is handled here: it is logged once, and the status of
# read_ports does not show it.
printf 'level=ERROR msg="read port failed" line=%d err=%s\n' "$line" "$(quote "$ERROR_MESSAGE")" >&2
fi
done
printf 'level=INFO msg="ports read" ok=%d total=%d\n' "$ok" "$#" >&2
}
test_read_ports.bats 32 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/log-an-error/.
setup() {
source "$BATS_TEST_DIRNAME/read_ports.sh"
dir=$(mktemp -d)
}
teardown() {
rm -rf "${dir:?}"
}
check() { # check WANT_PORTS WANT_LOG TEXT...
local want_ports=$1 want_log=$2
shift 2
read_ports "$@" >"$dir/ports" 2>"$dir/log"
printf '%s' "$want_ports" >"$dir/want_ports"
printf '%s' "$want_log" >"$dir/want_log"
cmp "$dir/ports" "$dir/want_ports" && cmp "$dir/log" "$dir/want_log"
}
@test "one-bad" { check $'8080\n443\n' $'level=ERROR msg="read port failed" line=2 err="not a number: \'x\'"\nlevel=INFO msg="ports read" ok=2 total=3\n' $'8080' $'x' $'443'; }
@test "all-good" { check $'80\n443\n' $'level=INFO msg="ports read" ok=2 total=2\n' $'80' $'443'; }
@test "out-of-range" { check $'' $'level=ERROR msg="read port failed" line=1 err="out of range: 70000"\nlevel=INFO msg="ports read" ok=0 total=1\n' $'70000'; }
@test "empty-list" { check $'' $'level=INFO msg="ports read" ok=0 total=0\n'; }
@test "empty-text" { check $'' $'level=ERROR msg="read port failed" line=1 err="not a number: \'\'"\nlevel=INFO msg="ports read" ok=0 total=1\n' $''; }
@test "boundary" { check $'1\n65535\n' $'level=ERROR msg="read port failed" line=3 err="out of range: 0"\nlevel=INFO msg="ports read" ok=2 total=3\n' $'1' $'65535' $'0'; }
@test "newline" { check $'' $'level=ERROR msg="read port failed" line=1 err="not a number: \'80\\nlevel=INFO msg=\\"all good\\"\'"\nlevel=INFO msg="ports read" ok=0 total=1\n' $'80\nlevel=INFO msg="all good"'; }
@test "backslash" { check $'' $'level=ERROR msg="read port failed" line=1 err="not a number: \'C:\\\\port\'"\nlevel=INFO msg="ports read" ok=0 total=1\n' $'C:\\port'; }
@test "carriage-return" { check $'' $'level=ERROR msg="read port failed" line=1 err="not a number: \'80\\r\'"\nlevel=INFO msg="ports read" ok=0 total=1\n' $'80\r'; }
@test "tab" { check $'' $'level=ERROR msg="read port failed" line=1 err="not a number: \'8\\t0\'"\nlevel=INFO msg="ports read" ok=0 total=1\n' $'8\t0'; }
References
- Logging HOWTO, The Python Documentation, When to use logging
- logging, The Python Standard Library, Logger Objects
- console: error() static method, MDN Web Docs, the introduction
- Logger, Java SE 25 API, Method Summary, log
- Level, Java SE 25 API, Field Summary, SEVERE
- Logging in C# and .NET, Microsoft Learn, Log level; Log exceptions
- slog, The Go standard library, the overview; TextHandler
- log, docs.rs, the crate description, Usage
- Dave Cheney, Don't just check errors, handle them gracefully, 27 April 2016, Only handle errors once
- Logging Cheat Sheet, OWASP Cheat Sheet Series, Data to exclude; Event collection
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag TFJ8M7 Edit this page History Report an error Markdown