|
183 | 183 | such characters in HTML. To translate URLs for inclusion in the HREF |
184 | 184 | attribute of an <A> tag, use urllib.quote(). |
185 | 185 |
|
| 186 | +log(fmt, ...): write a line to a log file; see docs for initlog(). |
| 187 | +
|
186 | 188 |
|
187 | 189 | Caring about security |
188 | 190 | --------------------- |
|
349 | 351 | Because no HTML interpretation is going on, the traceback will |
350 | 352 | readable. |
351 | 353 |
|
| 354 | +When all else fails, you may want to insert calls to log() to your |
| 355 | +program or even to a copy of the cgi.py file. Note that this requires |
| 356 | +you to set cgi.logfile to the name of a world-writable file before the |
| 357 | +first call to log() is made! |
| 358 | +
|
352 | 359 | Good luck! |
353 | 360 |
|
354 | 361 |
|
|
409 | 416 | import sys |
410 | 417 | import os |
411 | 418 |
|
| 419 | + |
| 420 | +# Logging support |
| 421 | +# =============== |
| 422 | + |
| 423 | +logfile = "" # Filename to log to, if not empty |
| 424 | +logfp = None # File object to log to, if not None |
| 425 | + |
| 426 | +def initlog(*allargs): |
| 427 | + """Write a log message, if there is a log file. |
| 428 | +
|
| 429 | + Even though this function is called initlog(), you should always |
| 430 | + use log(); log is a variable that is set either to initlog |
| 431 | + (initially), to dolog (once the log file has been opened), or to |
| 432 | + nolog (when logging is disabled). |
| 433 | +
|
| 434 | + The first argument is a format string; the remaining arguments (if |
| 435 | + any) are arguments to the % operator, so e.g. |
| 436 | + log("%s: %s", "a", "b") |
| 437 | + will write "a: b" to the log file, followed by a newline. |
| 438 | +
|
| 439 | + If the global logfp is not None, it should be a file object to |
| 440 | + which log data is written. |
| 441 | +
|
| 442 | + If the global logfp is None, the global logfile may be a string |
| 443 | + giving a filename to open, in append mode. This file should be |
| 444 | + world writable!!! If the file can't be opened, logging is |
| 445 | + silently disabled (since there is no safe place where we could |
| 446 | + send an error message). |
| 447 | +
|
| 448 | + """ |
| 449 | + global logfp, log |
| 450 | + if logfile and not logfp: |
| 451 | + try: |
| 452 | + logfp = open(logfile, "a") |
| 453 | + except IOError: |
| 454 | + pass |
| 455 | + if not logfp: |
| 456 | + log = nolog |
| 457 | + else: |
| 458 | + log = dolog |
| 459 | + apply(log, allargs) |
| 460 | + |
| 461 | +def dolog(fmt, *args): |
| 462 | + """Write a log message to the log file. See initlog() for docs.""" |
| 463 | + logfp.write(fmt%args + "\n") |
| 464 | + |
| 465 | +def nolog(*allargs): |
| 466 | + """Dummy function, assigned to log when logging is disabled.""" |
| 467 | + pass |
| 468 | + |
| 469 | +log = initlog # The current logging function |
| 470 | + |
| 471 | + |
412 | 472 | # Parsing functions |
413 | 473 | # ================= |
414 | 474 |
|
|
0 commit comments