Giter Club home page Giter Club logo

Comments (6)

bitprophet avatar bitprophet commented on July 19, 2024

Calling out #546 and #547 as recently filed tickets with specifically phrased use cases that fall under this aegis.

from invoke.

gitaarik avatar gitaarik commented on July 19, 2024

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.

anarcat avatar anarcat commented on July 19, 2024

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.

gitaarik avatar gitaarik commented on July 19, 2024

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.

anarcat avatar anarcat commented on July 19, 2024

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:

https://gitweb.torproject.org/admin/tsa-misc.git/tree/fabric_tpa/decom.py?id=2698d3e0ece4de7ae4059f7a51860555e607a570#n100

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.

anarcat avatar anarcat commented on July 19, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.