Skip to content

Add logging features - #143

Merged
tfardet merged 31 commits into
InseeFrLab:masterfrom
tgrandje:logging-features
Jun 5, 2023
Merged

tfardet merged 31 commits into
InseeFrLab:masterfrom
tgrandje:logging-features

Conversation

@tgrandje

Copy link
Copy Markdown
Collaborator

Starting anew, replace all prints by logging features.

Logging's levels should be cautiously reviewed.

To activate the "verbose" mode, use the following :

import logging
logging.basicConfig(level=logging.DEBUG)
from pynsee.localdata import get_geo_list
df = get_geo_list("regions", update=True)

@tgrandje

Copy link
Copy Markdown
Collaborator Author

@tfardet that should be easier to follow !

@codecov-commenter

codecov-commenter commented May 12, 2023 •

Copy link
Copy Markdown

Codecov Report

Merging #143 (5b05cf0) into master (c630e22) will increase coverage by 0.00%.
The diff coverage is 88.28%.

❗ Your organization is not using the GitHub App Integration. As a result you may experience degraded service beginning May 15th. Please install the Github App Integration for your organization. Read more.

@@           Coverage Diff           @@
##           master     #143   +/-   ##
=======================================
  Coverage   92.29%   92.30%           
=======================================
  Files         117      117           
  Lines        3791     3795    +4     
=======================================
+ Hits         3499     3503    +4     
  Misses        292      292           
Impacted Files Coverage Δ
pynsee/localdata/get_old_city.py 80.95% <ø> (ø)
pynsee/utils/_get_credentials.py 73.91% <42.85%> (ø)
pynsee/download/get_column_metadata.py 93.18% <50.00%> (ø)
pynsee/download/_load_data_from_schema.py 69.81% <54.54%> (ø)
pynsee/localdata/get_area_list.py 94.00% <66.66%> (ø)
pynsee/metadata/get_legal_entity.py 78.26% <66.66%> (ø)
pynsee/utils/init_conn.py 93.47% <71.42%> (ø)
pynsee/macrodata/get_dataset_list.py 88.63% <75.00%> (ø)
pynsee/utils/_request_insee.py 77.50% <76.66%> (ø)
pynsee/localdata/_get_geo_list_simple.py 94.28% <80.00%> (-2.69%) ⬇️
... and 34 more

📣 We’re building smart automated test selection to slash your CI/CD build times. Learn more

@tfardet

tfardet commented May 15, 2023 •

Copy link
Copy Markdown
Collaborator

@tgrandje I don't think the later commits should have been added to this branch, could you revert these changes, please?

EDIT: If you're not familiar with git, you can just make a new branch from logging-features, then move back to logging-features and do a git reset --hard the-last-good-commit-hash and do a git push --force

@tgrandje

tgrandje commented May 15, 2023 •

Copy link
Copy Markdown
Collaborator Author

Yes, @tfardet I have blundered (again) with git; I tried to import this branch into a local project... That was done through github's interface and I'm searching for the appropriate way to rollback.

@tgrandje
tgrandje force-pushed the logging-features branch from f759dc1 to 5789cb2 Compare May 15, 2023 15:58
@tgrandje

Copy link
Copy Markdown
Collaborator Author

@tfardet thanks for your tip, I think this is ok now...

@tfardet tfardet left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, this was a big PR ^^"
Thanks for the hard work @tgrandje and @lgeo3 !

There are a few things that need changing and some things that should be removed (you can just copy the old code where it belongs and push it with the new commits to "undo" the changes)

@hadrilec there are a few decisions to be made regarding what people using the library should see by default; I tagged you on the comments where I think discussion is needed so you can just search for your handle

def warning_file(missingFile, foundFile):

print(f"Data file missing in the zip file:\n{missingFile}")
msg = f"Data file missing in the zip file:\n{missingFile}\n"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need the newline at the end?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We do not need it ; but it may be easier to read the log if it is splitted among multiple lines (as it used to be with multiple prints).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

while developing the package, I might have thought back then that it was easier to read, feel free to remove it


else:
print("No column-specific metadata has been found for this file")
logger.info("No column-specific metadata has been found for this file")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds more like a warning to me

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure metadata are meant to be found each time (you still get a dataframe), but yes we could definitely change it to warning.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed, it should be a warning

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In fact,_add_metadata isn't used anymore in the project and has been "commented out" (transformed into a string to be precise) since that commit. @hadrilec should we remove it altogether ?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unless I have not understood this commit, I think the message is still relevant. @tgrandje could you please elaborate on why you think the message should be removed? Thanks

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I confirm that this function has been commented out:

def _add_metadata(id, df):

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hadrilec I didn't comment it out, it's due to your previous PR (might be because the function is not called anymore in the project ?)

print("Please report this issue")
msg += "No replacement file has been found\n"
msg += "Please report this issue !"
logger.error(msg)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately we need to separate here:

  • an error in the if block
  • a warning in the else block

One cannot just use error for both after the if-else block

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd say this is still an error if you tried to get a file and no file has been found (wether or not you found a replacement file which may be outdated). But in case we want to change the behaviour we could use a getattr. Something like this :

if blah:
  method = "warning"
else:
  method = "error"
getattr(logger, method)("Blah")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cc @hadrilec for discussion (I have no strong opinion here)

Comment thread pynsee/download/get_column_metadata.py Outdated
labels = labels.reset_index(drop=True)
else:
print("Columns labels not found in metadata")
logger.info("Columns labels not found in metadata")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would use warning here

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment about metadata (I'm not sure if there are case when this is "normal")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

indeed, it should be a warning

Comment thread pynsee/download/get_file_list.py Resolved
Comment thread pynsee/utils/_wait_api_query_limit.py Outdated
n_query = len(qCount.index)

# print("n query in 1 min : %s" % n_query)
# logger.info("n query in 1 min : %s" % n_query)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

delete or uncomment (moving it to debug)? cc @hadrilec

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it should be deleted

Comment thread pynsee/utils/_wait_api_query_limit.py Outdated
# time.sleep(1)
_warning_query_limit()
# print("\nWai!ting time - %s secs" % waiting_time)'
# logger.info("\nWai!ting time - %s secs" % waiting_time)'

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

delete? cc @hadrilec

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it should be deleted

Comment thread pynsee/utils/_warning_cached_data.py Resolved
Comment thread pynsee/utils/init_conn.py Outdated
)
else:
print(f"Token has been created")
logger.debug(f"Token has been created")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move to info

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure you need to "info" that : it the token generation fails, you get an exception anyway, so that seems obvious to me.

@tfardet tfardet May 16, 2023 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the way I see it, someone not working on pynsee may want to check that all went well (e.g. to confirm an error in their script does not come from there), whereas debug is strictly limited to things that require an understanding of the library's internals and that would be used to debug of the library itself (and not just of a script using the library)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it should be printed as an info message

Comment thread pyproject.toml.poetry.back Outdated
@@ -0,0 +1,24 @@
[tool.poetry]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

delete file

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it can be deleted

@tgrandje

Copy link
Copy Markdown
Collaborator Author

Thanks @tfardet ! Sorry for the multiple notifications and the undesired "changes" (probably linked to me blundering with git and recreating the fork from @lgeo3's own fork). I'll wait for @hadrilec 's return before updating the PR.

@tfardet tfardet linked an issue May 16, 2023 that may be closed by this pull request
@tgrandje

Copy link
Copy Markdown
Collaborator Author

Btw @tfardet : will git keep the nested conversations at the right place if I push further comits ?

@tfardet

tfardet commented May 16, 2023 •

Copy link
Copy Markdown
Collaborator

will git keep the nested conversations at the right place if I push further comits ?

it should, unless the commit changes that line (in which case the conversation is hidden as "outdated" by default, if I remember correctly; note that this is github specific, btw, PRs do not exist in git)

tgrandje added 16 commits May 16, 2023 14:02
Revert to current master (including black formatting)
_get_geodata is not used in _add_insee_dep anymore
* black formatting
* explicit exceptions
Fix proxies declaration and process each one separately (in case only one proxy is set among http / https)
Move session with "with statement" for automatic closure
Use a with statement which will revert the default configuration on closure.
Add link to log with error entry + add link to infered dataframe returned by the function.
* removed "\n"
* black formating
* revert to master
* black formating
* fix docstring on get_geo_list
* explicit exceptions
* print -> logger.info (awaiting review)
* revert to master
* black formatting
* fix proxies declaration (in case of only one of http/https proxy is set)
* explicit exceptions
* fix urllib3 warnings catchment with "with statement" for automatic reversal
* black formatting
* change logger's level to info on self-update entry
Remove blank lines from log
* revert to master
* black formatting
tgrandje added 5 commits May 16, 2023 14:52
explicit exception
Reset logger's levels in get_seirene_data and search_sirene
+ black formatting
* revert to master
* black formatting
* print -> logger
* fix proxies declaration (in case of any one http / https missing)
Black formatting + set logger's level to info on token creation
@tgrandje

Copy link
Copy Markdown
Collaborator Author

@tfardet this should handle the most problematic conflicts and the case where there was no debate (I'll let you resolve conversation in any case).
As "black linting" was now set on my editor (and as this shouldn't cause any trouble) I let it format all changed files.

I've also taken the liberty to commit small changes on the side (mostly one bug on proxies declaration, explicit exceptions and remove the call of unused submodules) ; that was done only when I had to rewrite a file to resolve the major conflicts.

tgrandje added 2 commits May 16, 2023 16:05
* reset session closure from master
* quick and dirty fix for session recreation during multiprocess (can be caused by _get_data_with_bbox's self call) to preserve proxies, backoff strategy, etc.
Black formatting has changed a bit more of get_legal_entity but this is not relevant.
@tfardet

tfardet commented May 20, 2023 •

Copy link
Copy Markdown
Collaborator

Alright, so I think we resolved all discussions, just summing it up here so it's easier to see:

PS: @tgrandje you'll have to do a pull from upstream and resolve the conflicts so that we can merge the PR since something else was merged into master in the meantime

tgrandje added 3 commits May 21, 2023 17:16
* Refatorization of PR's code according to reviews
* Added an harmonisation of caching info for macrodata (specifying the downloaded file's location)
* Black formatting

@tfardet tfardet left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, getting there! There is still the matter of the changes that should not have been in this PR and that still need to be removed and one question for @hadrilec and then I think we're good ;)

@lru_cache(maxsize=None)
def _get_geo_list_simple(geo, progress_bar=False):

def _get_geo_list_simple(geo, date=None, progress_bar=False):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tgrandje this still needs to be removed ;)

import pandas as pd
from tqdm import trange
import numpy as np
from requests.exceptions import RequestException

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

still true

insee_folder = _create_insee_folder()
file_localdata = insee_folder + "/" + filename

RENAME = {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove from this PR

@lru_cache(maxsize=None)
def _warning_get_new_city():
print("\ndate is None, by default it supposed to be ten years before current year")
logger.info(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hadrilec I thought we had answered all question, but I'm actually not sure we dealt with this one...

Comment thread pynsee/macrodata/_get_insee.py Outdated

if len(list_obs) > 0:
obs_series = pd.concat(list_obs).reset_index(drop=True)
obs_series = pd.concat(list_obs)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

readd reset_index

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, that one's on me; can't see how I missed the changes to master in this file, but I'll correct this asap.

dict_attr[a] = attr_series[a]._value

col_attr = list(dict_attr.keys())
attr_series = pd.DataFrame(dict_attr, columns=col_attr, index=[0]).reset_index(drop=True)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

idem

@tgrandje

Copy link
Copy Markdown
Collaborator Author

@tfardet ok, so I think I'm done here. As you said, big PR and so I missed your last comments (which explains the multiple commits here). Some things where not explicitly discussed, but I think that it should be good enough as it is.

Btw, I've also taken the liberty to reset the ex-prints from macrodata and harmonised it with all other caching/restoring files' logging system. I've also kept your suggestion about "pynsee_query_print" in _request_insee to keep it simple, but I think your first assumption (ie that we don't need it anymore) should be better in the long run.

I've still a strange feeling about the warning on credentials. I'm convinced there are as many (or less) risks when using environment variables as with plain strings in a script file (which won't trigger any warnings). Or am I missing something here ?
That being said, in both cases strings may be stored in the file and end up on github. This is the case indeed with the code shared in the readme (the os.environ[...] = ... statement). I think we should take the opportunity to update the readme with a reference to something like python_dotenv to enhance security.

@tfardet

tfardet commented May 21, 2023

Copy link
Copy Markdown
Collaborator

ok, so I think I'm done here. As you said, big PR and so I missed your last comments (which explains the multiple commits here). Some things where not explicitly discussed, but I think that it should be good enough as it is.

almost, sorry (see review above)

Btw, I've also taken the liberty to reset the ex-prints from macrodata and harmonised it with all other caching/restoring files' logging system. I've also kept your suggestion about "pynsee_query_print" in _request_insee to keep it simple, but I think your first assumption (ie that we don't need it anymore) should be better in the long run.

Good.

I've still a strange feeling about the warning on credentials. I'm convinced there are as many (or less) risks when using environment variables as with plain strings in a script file (which won't trigger any warnings). Or am I missing something here ?
That being said, in both cases strings may be stored in the file and end up on github. This is the case indeed with the code shared in the readme (the os.environ[...] = ... statement). I think we should take the opportunity to update the readme with a reference to something like python_dotenv to enhance security.

Credential management is currently as bad as it gets and if someone could have a look and improve it, that would be great; in the meantime, however, better make sure that people get notified about the fact that they are not using the process that is described in the tutorial, just in case they did a set and forget in some profile file and then updated their credentials via the script (or just decided to try to use a one-time credential via the library's API).

@hadrilec

hadrilec commented May 21, 2023 •

Copy link
Copy Markdown
Contributor

I agree that credentials management can be improved.
If you have some ideas, dont hesitate to make proposals.

Using os.environ[...] allows the package to be tested by GitHub Action with secret values.
Those values can also be stored in python session startup tools automatically.
In these two cases, init_conn is not used whereas valid credentials are.

the os variable pynsee_query_print has been mainly meant to be used for debbuging purposes so I guess a debugging logger could be used instead

@tgrandje

Copy link
Copy Markdown
Collaborator Author

To be clear, I'm perfectly happy with the credentials management de way it is :-) . I just disagree with the fact that environment variables need more caution (and thus warnings) than regular variables stored in a script (especially with init_con storing uncrypted credentials in the user's directory under the hood) .

Noted about pynsee_query_print, I'll change that.

tgrandje added 3 commits May 22, 2023 09:53
* remove pynsee_query_print
* black formatting
* revert get_insee to master
* black formatting
@tgrandje

Copy link
Copy Markdown
Collaborator Author

@tfardet I just finished reverting _get_insee to master. But I don't see anything in the code which relates to any caching of data ? The file is deleted (Which explains why I didn't harmonised the message with other "caching" messages and let the level be debug for now.)

@tgrandje

tgrandje commented Jun 1, 2023

Copy link
Copy Markdown
Collaborator Author

@tfardet did you had the time to review the last changes?

@tfardet

tfardet commented Jun 1, 2023

Copy link
Copy Markdown
Collaborator

@tgrandje I don't think my last series of comments where addressed: get_geo_list still has changes that do not belong to this PR.

@tgrandje
tgrandje requested a review from tfardet June 1, 2023 11:22
@tgrandje

tgrandje commented Jun 1, 2023 •

Copy link
Copy Markdown
Collaborator Author

@tfardet it was adressed (sorry: I thought I had commented it but apparently not explicitly enough).
The current state of the PR should normally be coherent with master's own state. Some of the changes you identified where already commited to master since this fork began and I fixed the conflicts directly in the branch (maybe I shouldn't have for things to be more clear).

@tfardet tfardet left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tgrandje mhh... you're right... I don't understand why it appears changed in the review interface... GitHub is really getting worse and worse since MS acquired it...

Anyways, looks good on my side, I restarted the failed job, just waiting to see whether it succeeds (or what went wrong if it doesn't)

@tfardet
tfardet merged commit 071a680 into InseeFrLab:master Jun 5, 2023
@tfardet

tfardet commented Jun 5, 2023

Copy link
Copy Markdown
Collaborator

Alright, it's in, thanks for the hard work!

tfardet pushed a commit to tfardet/pynsee that referenced this pull request May 11, 2025
Co-authored-by: thomas.grandjean <[email protected]>
Former-commit-id: 071a680
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use logging instead of print

4 participants