1

I want to log something to a text file using the Prometheus Python Client, with the below code. Just these three lines for testing purposes:

from prometheus_client import CollectorRegistry, write_to_textfile

registry = CollectorRegistry()
write_to_textfile('~/log.prom', registry)

when running the script an error is thrown that the file does not exist. The file ~/log.prom exists, but ~/log.prom.3872.139652924150208 does not... this filename also changes every time when running the script.

Traceback (most recent call last):
  File "/home/joost/log-to-text.py", line 4, in <module>
    write_to_textfile('~/log.prom', registry)
  File "/home/joost/.local/lib/python3.10/site-packages/prometheus_client/exposition.py", line 303, in write_to_textfile
    with open(tmppath, 'wb') as f:
FileNotFoundError: [Errno 2] No such file or directory: '~/log.prom.3872.139652924150208'

Not sure what is messing this up, just following the code snippet in the github documentation https://github.com/prometheus/client_python#node-exporter-textfile-collector

Josephus87
  • 1,126
  • 9
  • 19
  • 1
    The tilde (`~`) is a Linux|Bash feature to represent the user's home directory. In Python, if you want to include `~` in a folder path, you need to explicitly [`os,path.expanduser`](https://docs.python.org/3/library/os.path.html#os.path.expanduser) to convert the `~` path to an OS-specific path (since you may be running Python on e.g. Windows). It's best to not use the tilde but provide either an absolute|relative folder path e.g. `log.prom` will create the file in the folder from which you ran the Python code. – DazWilkin Feb 20 '23 at 18:10
  • @DazWilkin that solved it. Haha, such a beginner's mistake – Josephus87 Feb 24 '23 at 07:16
  • I'm pleased to hear it. It's intuitive to expect it to work in Python. Unfortunately, it doesn't. – DazWilkin Feb 24 '23 at 17:17

0 Answers0