本文整理匯總了Golang中github.com/mongodb/mongo-tools/common/log.Logf函數的典型用法代碼示例。如果您正苦於以下問題:Golang Logf函數的具體用法?Golang Logf怎麽用?Golang Logf使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Logf函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: BuildWriteConcern
// BuildWriteConcern takes a string and a NodeType indicating the type of node the write concern
// is intended to be used against, and converts the write concern string argument into an
// mgo.Safe object that's usable on sessions for that node type.
func BuildWriteConcern(writeConcern string, nodeType NodeType) (*mgo.Safe, error) {
sessionSafety, err := constructWCObject(writeConcern)
if err != nil {
return nil, err
}
if sessionSafety == nil {
log.Logf(log.DebugLow, "using unacknowledged write concern")
return nil, nil
}
// for standalone mongods, set the default write concern to 1
if nodeType == Standalone {
log.Logf(log.DebugLow, "standalone server: setting write concern %v to 1", w)
sessionSafety.W = 1
sessionSafety.WMode = ""
}
var writeConcernStr interface{}
if sessionSafety.WMode != "" {
writeConcernStr = sessionSafety.WMode
} else {
writeConcernStr = sessionSafety.W
}
log.Logf(log.Info, "using write concern: %v='%v', %v=%v, %v=%v, %v=%v",
w, writeConcernStr,
j, sessionSafety.J,
fSync, sessionSafety.FSync,
wTimeout, sessionSafety.WTimeout,
)
return sessionSafety, nil
}
示例2: handleBSONInsteadOfDirectory
// handleBSONInsteadOfDirectory updates -d and -c settings based on
// the path to the BSON file passed to mongorestore. This is only
// applicable if the target path points to a .bson file.
//
// As an example, when the user passes 'dump/mydb/col.bson', this method
// will infer that 'mydb' is the database and 'col' is the collection name.
func (restore *MongoRestore) handleBSONInsteadOfDirectory(path string) error {
// we know we have been given a non-directory, so we should handle it
// like a bson file and infer as much as we can
if restore.ToolOptions.Collection == "" {
// if the user did not set -c, use the file name for the collection
newCollectionName, fileType := restore.getInfoFromFilename(path)
if fileType != BSONFileType {
return fmt.Errorf("file %v does not have .bson extension", path)
}
restore.ToolOptions.Collection = newCollectionName
log.Logf(log.DebugLow, "inferred collection '%v' from file", restore.ToolOptions.Collection)
}
if restore.ToolOptions.DB == "" {
// if the user did not set -d, use the directory containing the target
// file as the db name (as it would be in a dump directory). If
// we cannot determine the directory name, use "test"
dirForFile := filepath.Base(filepath.Dir(path))
if dirForFile == "." || dirForFile == ".." {
dirForFile = "test"
}
restore.ToolOptions.DB = dirForFile
log.Logf(log.DebugLow, "inferred db '%v' from the file's directory", restore.ToolOptions.DB)
}
return nil
}
示例3: dumpQueryToWriter
// dumpQueryToWriter takes an mgo Query, its intent, and a writer, performs the query,
// and writes the raw bson results to the writer. Returns a final count of documents
// dumped, and any errors that occured.
func (dump *MongoDump) dumpQueryToWriter(
query *mgo.Query, intent *intents.Intent) (int64, error) {
var total int
var err error
if len(dump.query) == 0 {
total, err = query.Count()
if err != nil {
return int64(0), fmt.Errorf("error reading from db: %v", err)
}
log.Logf(log.DebugLow, "counted %v %v in %v", total, docPlural(int64(total)), intent.Namespace())
} else {
log.Logf(log.DebugLow, "not counting query on %v", intent.Namespace())
}
dumpProgressor := progress.NewCounter(int64(total))
bar := &progress.Bar{
Name: intent.Namespace(),
Watching: dumpProgressor,
BarLength: progressBarLength,
}
dump.progressManager.Attach(bar)
defer dump.progressManager.Detach(bar)
err = dump.dumpIterToWriter(query.Iter(), intent.BSONFile, dumpProgressor)
_, dumpCount := dumpProgressor.Progress()
return dumpCount, err
}
示例4: determineOplogCollectionName
// determineOplogCollectionName uses a command to infer
// the name of the oplog collection in the connected db
func (dump *MongoDump) determineOplogCollectionName() error {
session := dump.SessionProvider.GetSession()
masterDoc := bson.M{}
err := session.Run("isMaster", &masterDoc)
if err != nil {
return fmt.Errorf("error running command: %v", err)
}
if _, ok := masterDoc["hosts"]; ok {
log.Logf(2, "determined cluster to be a replica set")
log.Logf(3, "oplog located in local.oplog.rs")
dump.oplogCollection = "oplog.rs"
return nil
}
if isMaster := masterDoc["ismaster"]; util.IsFalsy(isMaster) {
log.Logf(1, "mongodump is not connected to a master")
return fmt.Errorf("not connected to master")
}
// TODO stop assuming master/slave, be smarter and check if it is really
// master/slave...though to be fair legacy mongodump doesn't do this either...
log.Logf(2, "not connected to a replica set, assuming master/slave")
log.Logf(3, "oplog located in local.oplog.$main")
dump.oplogCollection = "oplog.$main"
return nil
}
示例5: Dump
// Dump handles some final options checking and executes MongoDump
func (dump *MongoDump) Dump() error {
err := dump.ValidateOptions()
if err != nil {
return fmt.Errorf("Bad Option: %v", err)
}
if dump.InputOptions.Query != "" {
// TODO, check for extended json support...
// gonna need to do some exploring later on, since im 95% sure
// this is undefined in the current tools
err = json.Unmarshal([]byte(dump.InputOptions.Query), &dump.query)
if err != nil {
return fmt.Errorf("error parsing query: %v", err)
}
}
if dump.OutputOptions.Out == "-" {
dump.useStdout = true
}
if dump.OutputOptions.DumpDBUsersAndRoles {
//first make sure this is possible with the connected database
dump.authVersion, err = auth.GetAuthVersion(dump.SessionProvider.GetSession())
if err != nil {
return fmt.Errorf("error getting auth schema version for dumpDbUsersAndRoles: %v", err)
}
log.Logf(2, "using auth schema version %v", dump.authVersion)
if dump.authVersion != 3 {
return fmt.Errorf("backing up users and roles is only supported for "+
"deployments with auth schema versions 3, found: %v", dump.authVersion)
}
}
//switch on what kind of execution to do
switch {
case dump.ToolOptions.DB == "" && dump.ToolOptions.Collection == "":
err = dump.DumpEverything()
case dump.ToolOptions.DB != "" && dump.ToolOptions.Collection == "":
err = dump.DumpDatabase(dump.ToolOptions.DB)
case dump.ToolOptions.DB != "" && dump.ToolOptions.Collection != "":
err = dump.DumpCollection(dump.ToolOptions.DB, dump.ToolOptions.Collection)
}
if dump.OutputOptions.DumpDBUsersAndRoles {
log.Logf(0, "dumping users and roles for %v", dump.ToolOptions.DB)
if dump.ToolOptions.DB == "admin" {
log.Logf(0, "skipping users/roles dump, already dumped admin database")
} else {
err = dump.DumpUsersAndRolesForDB(dump.ToolOptions.DB)
if err != nil {
return fmt.Errorf("error dumping users and roles: %v", err)
}
}
}
log.Logf(1, "done")
return err
}
示例6: CreateIntentForCollection
// CreateIntentForCollection builds an intent for the given database and collection name
// along with a path to a .bson collection file. It searches the file's parent directory
// for a matching metadata file.
//
// This method is not called by CreateIntentsForDB,
// it is only used in the case where --db and --collection flags are set.
func (restore *MongoRestore) CreateIntentForCollection(db string, collection string, dir archive.DirLike) error {
log.Logf(log.DebugLow, "reading collection %v for database %v from %v",
collection, db, dir.Path())
// first make sure the bson file exists and is valid
_, err := dir.Stat()
if err != nil {
return err
}
if dir.IsDir() {
return fmt.Errorf("file %v is a directory, not a bson file", dir.Path())
}
baseName, fileType := restore.getInfoFromFilename(dir.Name())
if fileType != BSONFileType {
return fmt.Errorf("file %v does not have .bson extension", dir.Path())
}
// then create its intent
intent := &intents.Intent{
DB: db,
C: collection,
Size: dir.Size(),
Location: dir.Path(),
}
intent.BSONFile = &realBSONFile{path: dir.Path(), intent: intent, gzip: restore.InputOptions.Gzip}
// finally, check if it has a .metadata.json file in its folder
log.Logf(log.DebugLow, "scanning directory %v for metadata", dir.Name())
entries, err := dir.Parent().ReadDir()
if err != nil {
// try and carry on if we can
log.Logf(log.Info, "error attempting to locate metadata for file: %v", err)
log.Log(log.Info, "restoring collection without metadata")
restore.manager.Put(intent)
return nil
}
metadataName := baseName + ".metadata.json"
if restore.InputOptions.Gzip {
metadataName += ".gz"
}
for _, entry := range entries {
if entry.Name() == metadataName {
metadataPath := entry.Path()
log.Logf(log.Info, "found metadata for collection at %v", metadataPath)
intent.MetadataLocation = metadataPath
intent.MetadataFile = &realMetadataFile{path: metadataPath, intent: intent, gzip: restore.InputOptions.Gzip}
break
}
}
if intent.MetadataFile == nil {
log.Log(log.Info, "restoring collection without metadata")
}
restore.manager.Put(intent)
return nil
}
示例7: Run
// Run creates and runs a parser with the Demultiplexer as a consumer
func (demux *Demultiplexer) Run() error {
parser := Parser{In: demux.In}
err := parser.ReadAllBlocks(demux)
if len(demux.outs) > 0 {
log.Logf(log.Always, "demux finishing when there are still outs (%v)", len(demux.outs))
}
log.Logf(log.DebugLow, "demux finishing (err:%v)", err)
return err
}
示例8: RestoreIntents
// RestoreIntents iterates through all of the intents stored in the IntentManager, and restores them.
func (restore *MongoRestore) RestoreIntents() error {
// start up the progress bar manager
restore.progressManager = progress.NewProgressBarManager(log.Writer(0), progressBarWaitTime)
restore.progressManager.Start()
defer restore.progressManager.Stop()
log.Logf(log.DebugLow, "restoring up to %v collections in parallel", restore.OutputOptions.NumParallelCollections)
if restore.OutputOptions.NumParallelCollections > 0 {
resultChan := make(chan error)
// start a goroutine for each job thread
for i := 0; i < restore.OutputOptions.NumParallelCollections; i++ {
go func(id int) {
log.Logf(log.DebugHigh, "starting restore routine with id=%v", id)
for {
intent := restore.manager.Pop()
if intent == nil {
log.Logf(log.DebugHigh, "ending restore routine with id=%v, no more work to do", id)
resultChan <- nil // done
return
}
err := restore.RestoreIntent(intent)
if err != nil {
resultChan <- fmt.Errorf("%v: %v", intent.Namespace(), err)
return
}
restore.manager.Finish(intent)
}
}(i)
}
// wait until all goroutines are done or one of them errors out
for i := 0; i < restore.OutputOptions.NumParallelCollections; i++ {
if err := <-resultChan; err != nil {
return err
}
}
return nil
}
// single-threaded
for {
intent := restore.manager.Pop()
if intent == nil {
return nil
}
err := restore.RestoreIntent(intent)
if err != nil {
return fmt.Errorf("%v: %v", intent.Namespace(), err)
}
restore.manager.Finish(intent)
}
return nil
}
示例9: validateReaderFields
// validateReaderFields is a helper to validate fields for input readers
func validateReaderFields(fields []string) error {
if err := validateFields(fields); err != nil {
return err
}
if len(fields) == 1 {
log.Logf(log.Info, "using field: %v", fields[0])
} else {
log.Logf(log.Info, "using fields: %v", strings.Join(fields, ","))
}
return nil
}
示例10: handlePut
// handle logic for 'put' command.
func (mf *MongoFiles) handlePut(gfs *mgo.GridFS) (output string, err error) {
localFileName := mf.getLocalFileName(nil)
// check if --replace flag turned on
if mf.StorageOptions.Replace {
err := gfs.Remove(mf.FileName)
if err != nil {
return "", err
}
output = fmt.Sprintf("removed all instances of '%v' from GridFS\n", mf.FileName)
}
var localFile io.ReadCloser
if localFileName == "-" {
localFile = os.Stdin
} else {
localFile, err = os.Open(localFileName)
if err != nil {
return "", fmt.Errorf("error while opening local file '%v' : %v\n", localFileName, err)
}
defer localFile.Close()
log.Logf(log.DebugLow, "creating GridFS file '%v' from local file '%v'", mf.FileName, localFileName)
}
gFile, err := gfs.Create(mf.FileName)
if err != nil {
return "", fmt.Errorf("error while creating '%v' in GridFS: %v\n", mf.FileName, err)
}
defer func() {
// GridFS files flush a buffer on Close(), so it's important we
// capture any errors that occur as this function exits and
// overwrite the error if earlier writes executed successfully
if closeErr := gFile.Close(); err == nil && closeErr != nil {
log.Logf(log.DebugHigh, "error occurred while closing GridFS file handler")
err = fmt.Errorf("error while storing '%v' into GridFS: %v\n", localFileName, closeErr)
}
}()
// set optional mime type
if mf.StorageOptions.ContentType != "" {
gFile.SetContentType(mf.StorageOptions.ContentType)
}
n, err := io.Copy(gFile, localFile)
if err != nil {
return "", fmt.Errorf("error while storing '%v' into GridFS: %v\n", localFileName, err)
}
log.Logf(log.DebugLow, "copied %v bytes to server", n)
output += fmt.Sprintf("added file: %v\n", gFile.Name())
return output, nil
}
示例11: DumpCollection
// DumpCollection dumps the specified database's collection
func (dump *MongoDump) DumpCollection(db, c string) error {
session := dump.SessionProvider.GetSession()
// in mgo, setting prefetch = 1.0 causes the driver to make requests for
// more results as soon as results are returned. This effectively
// duplicates the behavior of an exhaust cursor.
session.SetPrefetch(1.0)
var findQuery *mgo.Query
switch {
case len(dump.query) > 0:
findQuery = session.DB(db).C(c).Find(dump.query)
case dump.InputOptions.TableScan:
// ---forceTablesScan runs the query without snapshot enabled
findQuery = session.DB(db).C(c).Find(nil)
default:
findQuery = session.DB(db).C(c).Find(nil).Snapshot()
}
if dump.useStdout {
log.Logf(0, "writing %v.%v to stdout", db, c)
return dump.dumpQueryToWriter(findQuery, os.Stdout)
} else {
dbFolder := filepath.Join(dump.OutputOptions.Out, db)
err := os.MkdirAll(dbFolder, 0755)
if err != nil {
return fmt.Errorf("error creating directory `%v`: %v", dbFolder, err)
}
outFilepath := filepath.Join(dbFolder, fmt.Sprintf("%v.bson", c))
out, err := os.Create(outFilepath)
if err != nil {
return fmt.Errorf("error creating bson file `%v`: %v", outFilepath, err)
}
defer out.Close()
log.Logf(0, "writing %v.%v to %v", db, c, outFilepath)
err = dump.dumpQueryToWriter(findQuery, out)
if err != nil {
return err
}
metadataFilepath := filepath.Join(dbFolder, fmt.Sprintf("%v.metadata.json", c))
metaOut, err := os.Create(metadataFilepath)
if err != nil {
return fmt.Errorf("error creating metadata.json file `%v`: %v", outFilepath, err)
}
defer metaOut.Close()
log.Logf(0, "writing %v.%v metadata to %v", db, c, metadataFilepath)
return dump.dumpMetadataToWriter(db, c, metaOut)
}
}
示例12: Convert
// Convert implements the Converter interface for JSON input. It converts a
// JSONConverter struct to a BSON document.
func (c JSONConverter) Convert() (bson.D, error) {
document, err := json.UnmarshalBsonD(c.data)
if err != nil {
return nil, fmt.Errorf("error unmarshaling bytes on document #%v: %v", c.index, err)
}
log.Logf(log.DebugHigh, "got line: %v", document)
bsonD, err := bsonutil.GetExtendedBsonD(document)
if err != nil {
return nil, fmt.Errorf("error getting extended BSON for document #%v: %v", c.index, err)
}
log.Logf(log.DebugHigh, "got extended line: %#v", bsonD)
return bsonD, nil
}
示例13: HeaderBSON
// HeaderBSON is part of the ParserConsumer interface and receives headers from parser.
// Its main role is to implement opens and EOFs of the embedded stream.
func (demux *Demultiplexer) HeaderBSON(buf []byte) error {
colHeader := NamespaceHeader{}
err := bson.Unmarshal(buf, &colHeader)
if err != nil {
return newWrappedError("header bson doesn't unmarshal as a collection header", err)
}
log.Logf(log.DebugHigh, "demux namespaceHeader: %v", colHeader)
if colHeader.Collection == "" {
return newError("collection header is missing a Collection")
}
demux.currentNamespace = colHeader.Database + "." + colHeader.Collection
if _, ok := demux.outs[demux.currentNamespace]; !ok {
if demux.NamespaceChan != nil {
demux.NamespaceChan <- demux.currentNamespace
err := <-demux.NamespaceErrorChan
if err == io.EOF {
// if the Prioritizer sends us back an io.EOF then it's telling us that
// it's finishing and doesn't need any more namespace announcements.
close(demux.NamespaceChan)
demux.NamespaceChan = nil
return nil
}
if err != nil {
return newWrappedError("failed arranging a consumer for new namespace", err)
}
}
}
if colHeader.EOF {
crc := int64(demux.hashes[demux.currentNamespace].Sum64())
length := int64(demux.lengths[demux.currentNamespace])
if crc != colHeader.CRC {
return fmt.Errorf("CRC mismatch for namespace %v, %v!=%v",
demux.currentNamespace,
crc,
colHeader.CRC,
)
}
log.Logf(log.DebugHigh,
"demux checksum for namespace %v is correct (%v), %v bytes",
demux.currentNamespace, crc, length)
demux.outs[demux.currentNamespace].Close()
delete(demux.outs, demux.currentNamespace)
delete(demux.hashes, demux.currentNamespace)
delete(demux.lengths, demux.currentNamespace)
// in case we get a BSONBody with this block,
// we want to ensure that that causes an error
demux.currentNamespace = ""
}
return nil
}
示例14: createIntentFromOptions
func (dump *MongoDump) createIntentFromOptions(dbName string, ci *collectionInfo) error {
if dump.shouldSkipCollection(ci.Name) {
log.Logf(log.DebugLow, "skipping dump of %v.%v, it is excluded", dbName, ci.Name)
return nil
}
intent, err := dump.NewIntent(dbName, ci.Name)
if err != nil {
return err
}
intent.Options = ci.Options
dump.manager.Put(intent)
log.Logf(log.DebugLow, "enqueued collection '%v'", intent.Namespace())
return nil
}
示例15: checkOplogTimestampExists
// checkOplogTimestampExists checks to make sure the oplog hasn't rolled over
// since mongodump started. It does this by checking the oldest oplog entry
// still in the database and making sure it happened at or before the timestamp
// captured at the start of the dump.
func (dump *MongoDump) checkOplogTimestampExists(ts bson.MongoTimestamp) (bool, error) {
oldestOplogEntry := db.Oplog{}
err := dump.sessionProvider.FindOne("local", dump.oplogCollection, 0, nil, []string{"+$natural"}, &oldestOplogEntry, 0)
if err != nil {
return false, fmt.Errorf("unable to read entry from oplog: %v", err)
}
log.Logf(log.DebugHigh, "oldest oplog entry has timestamp %v", oldestOplogEntry.Timestamp)
if oldestOplogEntry.Timestamp > ts {
log.Logf(log.Info, "oldest oplog entry of timestamp %v is older than %v",
oldestOplogEntry.Timestamp, ts)
return false, nil
}
return true, nil
}