potassco / clingo

šŸ¤” A grounder and solver for logic programs.
https://potassco.org/clingo
MIT License
589 stars 79 forks source link

Capture the logger #478

Closed MaxOstrowski closed 5 months ago

MaxOstrowski commented 5 months ago

I want to redirect the log from gringo to my own logger, s.t. everything is nice and ordered: The following program ends with an exception of a syntax error, which is expected. But the logging seems to report an additional error:

import logging
from clingo.ast import parse_string

def main() -> None:
    prg = []
    parse_string("*", prg.append, logger=logging.warning)

if __name__ == "__main__":
    main()

produces

--- Logging error ---
Traceback (most recent call last):
  File "...miniconda3/envs/ngo/lib/python3.10/logging/__init__.py", line 1100, in emit
    msg = self.format(record)
  File "...miniconda3/envs/ngo/lib/python3.10/logging/__init__.py", line 943, in format
    return fmt.format(record)
  File "...miniconda3/envs/ngo/lib/python3.10/logging/__init__.py", line 678, in format
    record.message = record.getMessage()
  File "...miniconda3/envs/ngo/lib/python3.10/logging/__init__.py", line 368, in getMessage
    msg = msg % self.args
TypeError: not all arguments converted during string formatting
Call stack:
  File "...work/krbiz/potassco/ngo/log.py", line 13, in <module> 
    main()
  File "...work/krbiz/potassco/ngo/log.py", line 10, in main 
    parse_string("*", prg.append, logger=logging.warning)
  File "...miniconda3/envs/ngo/lib/python3.10/site-packages/clingo/ast.py", line 1347, in parse_string
    _lib.clingo_ast_parse_string(
  File "...miniconda3/envs/ngo/lib/python3.10/site-packages/clingo/core.py", line 95, in _pyclingo_logger_callback
    handler(MessageCode(code), _to_str(message))
Message: <MessageCode.RuntimeError: 1>
Arguments: ('<string>:1:1-2: error: syntax error, unexpected *\n',)
Traceback (most recent call last):
  File "...work/krbiz/potassco/ngo/log.py", line 13, in <module> 
    main()
  File "...work/krbiz/potassco/ngo/log.py", line 10, in main 
    parse_string("*", prg.append, logger=logging.warning)
  File "...miniconda3/envs/ngo/lib/python3.10/site-packages/clingo/ast.py", line 1346, in parse_string
    _handle_error(
  File "...miniconda3/envs/ngo/lib/python3.10/site-packages/clingo/_internal.py", line 75, in _handle_error
    raise RuntimeError(msg)
RuntimeError: syntax error

How can I handle this case correctly ?

rkaminsk commented 5 months ago

logging.warning and the clingo logger do not have the same signature. You'll have to write some wrapper code. Check the type annotations!

MaxOstrowski commented 5 months ago

Thank you, my mistake, fixed it.