Comments (6)
Calling out #546 and #547 as recently filed tickets with specifically phrased use cases that fall under this aegis.
from invoke.
So what's the work need to be done here? Just use Python's logging module instead of print()
statements? That shouldn't be too hard? I could do a pull request.
I assume you want to log the output of the command, and with logging formatting you can control whether the command itself is shown and whether the hostname is shown?
So something like:
c.run('ls')
Would output something like:
file1 file2 file3
And:
import logging
logging.basicConfig(format="%(command)s\n%(output)s")
c.run('ls')
Would output something like:
ls
file1 file2 file3
and
import logging
logging.basicConfig(format="[%(hostname)] %(command)s\n%(output)s")
c.run('ls')
Would output something like:
[myhost] ls
file1 file2 file3
Am I on the right track here?
from invoke.
in stressant, i add a logging output level called OUTPUT
to log command standard output, for what that's worth. it's kind of nasty, but it works. i'm thinking of rewriting stresssant with invoke, so i'd be very interested in seeing how this could work.
i call the logging function once per line, that said, not once per command. maybe that's bad, but i need this to show that stuff on the console, so i had no way around that that i found elegant.
from invoke.
I've created my own run()
and cd()
methods for now that print the logging that I want:
from textwrap import indent
class Color:
# Terminal text color escape characters
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
def run(conn, command, sudo_pass=None):
"""
At the time of writing, Fabric 2 doesn't have a way to show the hostname in
front of the command. So we do it manually here.
This GitHub issue is working on solving this in Fabric 2:
https://github.com/pyinvoke/invoke/issues/15
"""
print(f"{Color.BOLD}[{conn.host}] {command}{Color.END}\n")
if sudo_pass:
result = conn.sudo(command, hide=True, echo=False, password=sudo_pass)
else:
result = conn.run(command, hide=True, echo=False)
output = indent(result.stdout or result.stderr, ' ')
print(output)
@contextmanager
def cd(conn, path):
"""
For the same reason we define our own `run()` command, we also have our own
`cd()` command so we can log elaborate output to the user.
Because this method should be a contextmanager, we can't use the original
`cd()` method, but we can mimic it's functionality, by updating the value
of `Connection.command_cwds`.
"""
print(f'\n{Color.BOLD}[{conn.host}] entering dir {path}{Color.END}\n')
conn.command_cwds.append(path)
try:
yield
finally:
print(f'\n{Color.BOLD}[{conn.host}] leaving dir {path}{Color.END}\n')
conn.command_cwds.pop()
from invoke.
after fiddling around with fabric for a few more days, one thing i'm missing is a --verbose
flag. we already have --debug
in the fab
commandline, which turns debugging all the way up to 11 (loglevel=DEBUG
), but i often send stuff to the INFO
level for some tasks.
for example, take this script:
it has a main()
because i want to setup logging so that when --verbose
passed to the script, i see those neat logging.info
messages come up. but by default, the script silently does its magic (more or less - it's not finished yet).
if fab had a --verbose
argument that did the right thing, i wouldn't need this main
at all! :)
(well, that's not true: that script is complicated by the fact that it operates on three different servers, so the task would at least need to be rewire just so, but still...)
update: i added #706 to show what i mean. probably incomplete... i wonder if another part of this would be to convert a precious few of the current debug
statement into info
level logs so that we would get some logging by default in "verbose"... (say "connecting to server", "runnin command" or something like that, instead of the flood of stuff from paramiko and Context we currently get...)
from invoke.
here's another hack I used:
class VerboseProgram(Fab):
# cargo-culted from fab's main.py
def __init__(self, *args, **kwargs):
super().__init__(*args,
executor_class=Executor,
config_class=Config,
**kwargs)
def core_args(self):
core_args = super().core_args()
extra_args = [
Argument(
names=('verbose', 'v'),
kind=bool,
default=False,
help="be more verbose"
),
]
return core_args + extra_args
def parse_core(self, argv):
super().parse_core(argv)
if self.args.debug.value:
logging.getLogger('').setLevel(logging.DEBUG)
elif self.args.verbose.value:
logging.getLogger('').setLevel(logging.INFO)
# reset formatter
logging.debug('reseting logging formats')
for h in logging.getLogger('').handlers:
f = logging.Formatter()
h.setFormatter(f)
# override default logging policies in submodules
#
# without this, we get debugging info from paramiko with --verbose
for mod in 'fabric', 'paramiko', 'invoke':
logging.getLogger(mod).setLevel('WARNING')
kind of clunky, but it seemed better than hacking up my own wrapper to a task, which is what i was doing before (and required duplicating the argument parsing logic).
from invoke.
Related Issues (20)
- Change default shell without a config file or Context? HOT 3
- Task decorator removes docstring HOT 1
- Run tasks relative to `tasks.py` HOT 2
- How to manually set short flags? HOT 1
- context.run(): Expose API to pass command and separate args instead of a single string HOT 2
- Specify a config file per Collection... possible?
- Collection mix-up when cross importing invoke tasks
- Running post tasks even if the main task fail
- `--help` after the command treats `--help` as positional argument HOT 2
- Is there support for making invoke.yaml context settings cli flags?
- EncodeWarning's when running on python >= 3.11
- @task(pre=[call(setup, 'qwe')]) fails with "NameError: name 'call' is not defined" HOT 1
- Config run should handle shell paths with spaces HOT 2
- Is it possible to only mock one command and run the rest with MockContext?
- autoprint generators correctly
- Generate help infomation of task args from function docstring.
- Importing Python modules from a scripts directory beside the tasks directory
- Recommended way to forward arguments to commands HOT 2
- Printing Promise objects from asynchronous Runner.run() raises Attribute Error
- Sudo showing password in clear
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from invoke.