3 #define SD_JOURNAL_SUPPRESS_LOCATION
4 #include <systemd/sd-journal.h>
8 PyDoc_STRVAR(journal_sendv__doc__,
9 "sendv('FIELD=value', 'FIELD=value', ...) -> None\n\n"
10 "Send an entry to the journal."
14 journal_sendv(PyObject *self, PyObject *args) {
15 struct iovec *iov = NULL;
16 int argc = PyTuple_Size(args);
20 PyObject **encoded = calloc(argc, sizeof(PyObject*));
22 ret = PyErr_NoMemory();
26 // Allocate sufficient iovector space for the arguments.
27 iov = malloc(argc * sizeof(struct iovec));
29 ret = PyErr_NoMemory();
33 // Iterate through the Python arguments and fill the iovector.
34 for (i = 0; i < argc; ++i) {
35 PyObject *item = PyTuple_GetItem(args, i);
39 if (PyUnicode_Check(item)) {
40 encoded[i] = PyUnicode_AsEncodedString(item, "utf-8", "strict");
41 if (encoded[i] == NULL)
45 if (PyBytes_AsStringAndSize(item, &stritem, &length))
48 iov[i].iov_base = stritem;
49 iov[i].iov_len = length;
52 // Clear errno, because sd_journal_sendv will not set it by
53 // itself, unless an error occurs in one of the system calls.
56 // Send the iovector to the journal.
57 r = sd_journal_sendv(iov, argc);
61 PyErr_SetFromErrno(PyExc_IOError);
63 PyErr_SetString(PyExc_ValueError, "invalid message format");
72 for (i = 0; i < argc; ++i)
73 Py_XDECREF(encoded[i]);
78 // Free the iovector. The actual strings
79 // are already managed by Python.
85 PyDoc_STRVAR(journal_stream_fd__doc__,
86 "stream_fd(identifier, priority, level_prefix) -> fd\n\n"
87 "Open a stream to journal by calling sd_journal_stream_fd(3)."
91 journal_stream_fd(PyObject *self, PyObject *args) {
92 const char* identifier;
93 int priority, level_prefix;
95 if (!PyArg_ParseTuple(args, "sii:stream_fd",
96 &identifier, &priority, &level_prefix))
99 fd = sd_journal_stream_fd(identifier, priority, level_prefix);
101 return PyErr_SetFromErrno(PyExc_IOError);
103 return PyLong_FromLong(fd);
106 static PyMethodDef methods[] = {
107 {"sendv", journal_sendv, METH_VARARGS, journal_sendv__doc__},
108 {"stream_fd", journal_stream_fd, METH_VARARGS,
109 journal_stream_fd__doc__},
110 {NULL, NULL, 0, NULL} /* Sentinel */
113 #if PY_MAJOR_VERSION < 3
118 (void) Py_InitModule("_journal", methods);
123 static struct PyModuleDef module = {
124 PyModuleDef_HEAD_INIT,
125 "_journal", /* name of module */
126 NULL, /* module documentation, may be NULL */
127 0, /* size of per-interpreter state of the module */
132 PyInit__journal(void)
134 return PyModule_Create(&module);