Commit 1754a5da authored by Gökçe Aydos's avatar Gökçe Aydos 🌈
Browse files

hint to must

parent 55339254
Pipeline #10792 passed with stage
in 6 minutes and 28 seconds
%% Cell type:markdown id:23d18708 tags:
# Q (4p)
Complete the following code so that the code writes a message to the file `usage.log` whenever a method is used.
Complete the following code so that the code writes a message to the file `usage.log` whenever a method is used. Use `logging` from the standard library.
Hint:
- use `logging` from the standard library
- Try restarting the kernel if you don't see `usage.log` or no new messages
%% Cell type:code id:509239c3 tags:
``` python
### BEGIN SOLUTION
import logging
logging.basicConfig(filename='usage.log', level=logging.DEBUG)
### END SOLUTION
class TodoList:
def __init__(self):
self.list = []
usage_msg = f'{__class__}: created'
### BEGIN SOLUTION
logging.info(usage_msg)
### END SOLUTION
def __iadd__(self, string):
self.list.append(string)
usage_msg = f'{__class__}: added {string}'
### BEGIN SOLUTION
logging.info(usage_msg)
### END SOLUTION
return self
```
%% Cell type:code id:d1a5780f tags:
``` python
# test if 'usage.log' is created
todolist = TodoList()
import os.path
assert os.path.isfile('usage.log')
!cat usage.log
```
%% Output
INFO:root:<class '__main__.TodoList'>: created
INFO:root:<class '__main__.TodoList'>: added call mom
INFO:root:<class '__main__.TodoList'>: created
%% Cell type:code id:41efa23d tags:
``` python
# test if new messages are added to 'usage.log'
with open('usage.log', 'w'):
pass # clear logfile
todolist = TodoList()
todolist += 'call mom'
todolist += 'call dad'
with open('usage.log') as f:
line_count = sum(1 for _ in f)
!cat usage.log
assert line_count == 3, f'{line_count} != 3'
```
%% Output
INFO:root:<class '__main__.TodoList'>: created
INFO:root:<class '__main__.TodoList'>: added call mom
INFO:root:<class '__main__.TodoList'>: added call dad
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment